将自定义类型转换为字符串
Convert custom type into string
给定 Clojurescript 中的自定义数据类型:
(deftype Foo [bar])
我希望能够使用 str
宏将此类型转换为字符串。 (str (->Foo "bar"))
的结果总是 "[object Object]"
。浏览各种文档和资源,我发现 IPrintWithWriter
协议允许我定义自定义字符串表示形式。所以下面的扩展非常接近我要找的东西:
(extend-type Foo
IPrintWithWriter
(-pr-writer [this writer _] (-write writer (str "test:" (.-bar this)))))
确实,当使用 (pr-str (->Foo "bla"))
时,return 值确实是字符串 "test:bla"
。但是,str
的 return 值保持 "[object Object]"
。
如何为 str
而不是 pr-str
提供 Foo
的自定义字符串表示形式?
ClojureScript 的 str
使用作为参数传递的对象的 Object.toString
方法:
(str x) returns x.toString()
您可以为您的 Foo
类型覆盖此方法:
(deftype Foo [bar]
Object
(toString [this]
(str "Test: " bar)))
;; => cljs.user/Foo
(str (->Foo "x"))
;; => "Test: x"
给定 Clojurescript 中的自定义数据类型:
(deftype Foo [bar])
我希望能够使用 str
宏将此类型转换为字符串。 (str (->Foo "bar"))
的结果总是 "[object Object]"
。浏览各种文档和资源,我发现 IPrintWithWriter
协议允许我定义自定义字符串表示形式。所以下面的扩展非常接近我要找的东西:
(extend-type Foo
IPrintWithWriter
(-pr-writer [this writer _] (-write writer (str "test:" (.-bar this)))))
确实,当使用 (pr-str (->Foo "bla"))
时,return 值确实是字符串 "test:bla"
。但是,str
的 return 值保持 "[object Object]"
。
如何为 str
而不是 pr-str
提供 Foo
的自定义字符串表示形式?
ClojureScript 的 str
使用作为参数传递的对象的 Object.toString
方法:
(str x) returns x.toString()
您可以为您的 Foo
类型覆盖此方法:
(deftype Foo [bar]
Object
(toString [this]
(str "Test: " bar)))
;; => cljs.user/Foo
(str (->Foo "x"))
;; => "Test: x"