在不存在的命名空间中命名 clojure 关键字是否有问题?
我是否应该对创建具有不存在的命名空间的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事实上,不会仅仅因为遇到“属于”它的关键字或符号而创建名称空间,如新 REPL 中的以下交互所示:
但是,这没有理由担心。关键字或符号的“命名空间”字段只是一个内部字符串;即使存在,也不会引用回所涉及的相应名称空间对象。事实上,如上所示,关键字和符号的
.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:
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.