Clojure defmacro loses metadata

前端 未结 2 741
醉酒成梦
醉酒成梦 2020-12-05 07:29

I am trying to create a little Clojure macro that defs a String with a type hint:

(defmacro def-string [name value]
  `(def ^String ~name ~value         


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 07:57

    ^ is a reader macro. defmacro never gets to see it. The hint is put on the list (unquote name). Compare for example (meta ^String 'x) with (meta ' ^String x) to see the effect.

    You need to put the hint on the symbol.

    (defmacro def-string
      [name value]
      `(def ~(vary-meta name assoc :tag `String) ~value))
    

    And the usage:

    user=> (def-string foo "bar")
    #'user/foo
    user=> (meta #'foo)
    {:ns #, :name foo, :file "NO_SOURCE_PATH", :line 5, :tag java.lang.String}
    

提交回复
热议问题