What are some uses of Clojure metadata?

后端 未结 4 1736
灰色年华
灰色年华 2020-12-14 15:55

How have you used metadata in your Clojure program?

I saw one example from Programming Clojure:

(defn shout [#^{:tag String} message] (.toUp         


        
4条回答
  •  悲&欢浪女
    2020-12-14 16:26

    • Docstrings are stored as metadata under the :doc key. This is probably the number 1 most apparent use of metadata.
    • Return and parameter types can be optionally tagged with metadata to improve performance by avoiding the overhead of reflecting on the types at runtime. These are also known as "type hints." #^String is a type hint.
    • Storing things "under the hood" for use by the compiler, such as the arglist of a function, the line number where a var has been defined, or whether a var holds a reference to a macro. These are usually automatically added by the compiler and normally don't need to be manipulated directly by the user.
    • Creating simple testcases as part of a function definition:

      (defn #^{:test (fn [] (assert true))} something [] nil)

      (test #'something)

    If you are reading Programming Clojure, then Chapter 2 provides a good intro to metadata. Figure 2.3 provides a good summary of common metadata.

提交回复
热议问题