提问人:Witek 提问时间:11/10/2023 更新时间:11/16/2023 访问量:69
Clojure/ClojureScript:如何插入 EDN 标签文字的自定义打印实现?
Clojure/ClojureScript: How to plug in custom print implementation for EDN tag literals?
问:
我有一个记录,一个实例,我把它打印到 EDN 字符串:
(ns my)
(defrecord Ref [type id])
(def rich (->Ref :Person 42)
(pr-str rich)
我想得到."#my.Ref [:Person 42]
但我明白了."#my.Ref{:type :Person, :id 23}"
播种如何插入我的自定义实现来打印实例?Ref
答:
5赞
Thomas Heller
11/10/2023
#1
在 CLJS 中,这是通过协议完成的。cljs.core/IPrintWithWriter
(extend-type Ref
IPrintWithWriter
(-pr-writer [this writer opts]
(-write writer "#my.Ref ")
(-pr-writer [(:type this) (:id this)] writer opts)))
在 CLJ 中,它是通过多方法完成的。clojure.core/print-method
(defmethod print-method Ref [this writer]
(.write writer "#my.Ref ")
(print-method [(:type this) (:id this)] writer))
评论
0赞
user2609980
11/15/2023
具体说来:(defmethod print-method Ref [this ^java.io.Writer w] (.write w (str "#my.Ref [" (:type this) " " (:id this) "]")))
2赞
Thomas Heller
11/16/2023
不建议这样做。上面的问题是它依赖于给定类型的 和 ,例如,它不能对 UUID 正常工作。最好总是回到实际的打印实现上,而不是盲目地把东西放在一起。你得到了编写器,直接使用它,不要手动将字符串连接在一起。我添加了一个完整的示例。.toString
:type
:id
str
评论