Clojure vars with metadata
Is it possible to create a new var with metadata without going through an "intermediate" var?
In开发者_开发百科 other words, I know I can do the following:
(def a-var 2)
(def another-var (with-meta a-var {:foo :bar}))
but is there any way to create another-var
without creating a-var
first?
Like this:
user> (def ^{:foo :bar} another-var 2)
#'user/another-var
user> (clojure.pprint/pprint (meta #'another-var))
{:ns #<Namespace user>,
:name another-var,
:file "NO_SOURCE_FILE",
:line 1,
:foo :bar}
nil
Also note, that (def another-var (with-meta a-var {:foo :bar}))
does not attach the metadata to the Var, but to the value. And since in your example a-var
holds an Integer, I wouldn't expect your example to work at all, since Integers can't hold metadata.
user=> (def a-var 2)
#'user/a-var
user=> (def another-var (with-meta a-var {:foo :bar}))
java.lang.ClassCastException: java.lang.Integer cannot be cast to clojure.lang.IObj (NO_SOURCE_FILE:2)
精彩评论