在不存在的命名空间中命名 clojure 关键字是否有问题?

发布于 2024-09-04 15:37:59 字数 146 浏览 2 评论 0原文

我是否应该对创建具有不存在的命名空间的 clojure 关键字感到谨慎?

一个例子是 :foo/bar,其中名称空间 foo 实际上并不存在。这似乎是可能的,因为这些关键字的行为就像文字一样。我在 REPL 中找不到任何问题,但我担心 AOT 编译可能出现问题。

Should I feel wary about creating clojure keywords which have non-existent namespaces?

An example would be :foo/bar, where namespace foo doesn't actually exist. This seems to be possible because these keywords behave like literals. I couldn't find any problems doing this in the REPL, but I'm concerned about possible problems with AOT compilation.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

二货你真萌 2024-09-11 15:37:59

事实上,不会仅仅因为遇到“属于”它的关键字或符号而创建名称空间,如新 REPL 中的以下交互所示:

; SLIME 2010-05-06
user> (-> (.getNamespace :user/foo) symbol)
user
user> (-> (.getNamespace :user/foo) symbol the-ns)
#<Namespace user>
user> (-> (.getNamespace :bar/foo) symbol the-ns)
; java.lang.Exception: No namespace: bar found

但是,这没有理由担心。关键字或符号的“命名空间”字段只是一个内部字符串;即使存在,也不会引用回所涉及的相应名称空间对象。事实上,如上所示,关键字和符号的 .getNamespace 方法返回一个字符串,并且必须跳转几跳才能从该字符串到达​​实际的命名空间。

尝试使用 resolve 函数解析命名空间限定的符号也是安全的。这与命名空间是否实际存在无关;如果不存在,则返回 nil,就像它确实存在的情况一样,但不包含给定名称的 Var。相反,如果找不到给定的命名空间,ns-resolve 将抛出一个异常,如上面 REPL 代码片段中提到的异常。

A namespace will in fact not be created simply because a keyword or symbol is encountered which would "belong" to it, as the following interaction at a fresh REPL illustrates:

; SLIME 2010-05-06
user> (-> (.getNamespace :user/foo) symbol)
user
user> (-> (.getNamespace :user/foo) symbol the-ns)
#<Namespace user>
user> (-> (.getNamespace :bar/foo) symbol the-ns)
; java.lang.Exception: No namespace: bar found

However, this is no cause for worry. A keyword's or symbol's "namespace" field is just an interned string; there is no reference back to the corresponding namespace object involved even if one exists. In fact, as can be seen above, the .getNamespace method of keywords and symbols returns a string and one has to jump a few hops to get to the actual namespace from that.

Trying to resolve a namespace-qualified symbol with the resolve function is safe too. That's regardless of whether the namespace actually exists; if it doesn't, nil is returned, as in the case where it does exist, but holds no Var of the given name. ns-resolve, in contrast, will throw an exception like the one mentioned in the snippet from the REPL above if it can't find the given namespace.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文