C-meta vs ^ {} - Clojure

I am confused about the differences between using with-meta and the reader macro ^ .

Attach baz symbol metadata using a reader macro

 user=> (def ^{:foo "bar"} baz {:my "value"}) #'user/baz 

pull it out

 user=> (meta #'baz) {:foo "bar", :ns #<Namespace user>, :name baz, :line 1, :file "NO_SOURCE_PATH"} 

using with-meta

 user=> (def (with-meta 'baz2 {:foo "bar"}) {:my "value"}) CompilerException java.lang.RuntimeException: First argument to def must be a Symbol, compiling:(NO_SOURCE_PATH:1) 

However...

 user=> (class (with-meta 'baz2 {:foo "bar"})) clojure.lang.Symbol 

I can attach it to a value

 user=> (def baz2 (with-meta {:my "value"} {:foo "bar"}) #'user/baz2 

but it is not the same

 user=> (meta baz2) {:foo "bar"} user=> (meta #'baz2) {:ns #<Namespace user>, :name baz2, :line 1, :file "NO_SOURCE_PATH"} 

can anyone explain this?

+6
source share
1 answer

def is a special form . Even if with-meta returns a character, the Clojure compiler does not know (cannot) know it. He sees a function.

 user=> (def (symbol blah) "blah") CompilerException java.lang.RuntimeException: First argument to def must be a Symbol, compiling:(NO_SOURCE_PATH:1) 
+5
source

Source: https://habr.com/ru/post/926441/


All Articles