Clojure/ClojureScript:如何插入 EDN 标签文字的自定义打印实现?

Wit*_*tek 2 clojure clojurescript edn

我有一条记录,一个实例,并将其打印到 EDN 字符串:

(ns my)
(defrecord Ref [type id])
(def rich (->Ref :Person 42)
(pr-str rich)
Run Code Online (Sandbox Code Playgroud)

我想得到"#my.Ref [:Person 42].

但我明白了"#my.Ref{:type :Person, :id 23}"

如何插入我的自定义实现来打印 的实例Ref

Tho*_*ler 5

在 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)))
Run Code Online (Sandbox Code Playgroud)

在 CLJ 中,它是通过clojure.core/print-method多种方法完成的。

(defmethod print-method Ref [this writer]
  (.write writer "#my.Ref ")
  (print-method [(:type this) (:id this)] writer))
Run Code Online (Sandbox Code Playgroud)

  • 不建议这样做。上面的问题是它依赖于给定类型 `:type` 和 `:id` 的 `.toString`,例如它对于 UUID 不能正常工作。总是最好依靠实际的打印实现,而不是盲目地将东西“串”在一起。您已获得编写器,可以直接使用它,并且不要手动将字符串连接在一起。我添加了一个完整的示例。 (2认同)