英文:
Reference a symbol in a Go package without knowing if you are in that package?
问题
假设在包A
中有一个名为F
的函数,我正在创建的一些代码需要调用它。我该如何调用它呢?
如果我从包A
外部调用它,我使用A.F(...)
,如果我在A
内部调用它,我使用F(...)
。但是如果我无法确定哪个是正确的,或者需要在两者之间进行字节完全相同的工作怎么办呢?
[注意:我认为这种情况会发生,因为根据我的经验和观察,这通常是一个安全的假设。即使没有技术原因,PHB和立法者也是荒谬行为的好来源。]
英文:
Assume there is a function F
in package A
that some code I'm creating needs to call. How do I call it?
If I'm Calling it from outside package A
, then I uses A.F(...)
and if I'm inside A
I uses F(...)
. But what if Murphy prevents me from knowing which is true or requires a byte identical line work in both?
[note: I'm taking it as a given that such a case will occur because, in my experience and observations, that is generally a safe assumption. Even in the absence of technical reasons for it, PHBs and legislators are good sources of the ridiculous.]
答案1
得分: 3
没有这样的语法。请注意以下几点:
-
禁止循环导入。这意味着一个包不能导入自身。因此,一个包不能使用
pkg.S
的语法来引用自己的符号S
,因为它无法导入自身。 -
即使解决了这个问题,注意一旦导入,包可以被赋予任意名称。例如,你可以这样做:
import bar "foo"
这将把包
"foo"
中的S
导入为bar.S
,而不是预期的foo.S
。
以下方法可以解决这个问题:
-
在包
"foo"
中创建一个内部对象foo
,其成员是foo
导出的符号。这样可以在foo
自身中使用foo.S
的语法,但这是一个糟糕的补救方法。 -
使用如下的导入声明:
import . "foo"
这允许你将包
"foo"
中的符号S
作为S
使用,即无需前缀。请注意,这种导入声明被称为点导入,被认为是不好的风格,如果你声明的符号集合/导入的包发生变化,可能会导致问题。
英文:
There is no such syntax. Observe the following things:
-
Cyclical imports are forbidden. This especially means that a package cannot import itself. Thus, a package cannot refer to one of its symbols
S
with thepkg.S
syntax because it will not be able to import itself. -
Even if you solved that problem, observe that packages can be given an arbitrary name once imported. For instance, you could do:
import bar "foo"
Which imports
S
from package"foo"
asbar.S
as opposed to the expectedfoo.S
.
The following things could be used to work around this:
-
In the package
"foo"
, create an internal objectfoo
whose members are the symbolsfoo
exports. This allows you to use thefoo.S
syntax infoo
itself, but is a horrible kludge. -
Use an import declaration like
import . "foo"
which allows you to use symbol
S
from package"foo"
asS
, i. e. without prefix. Notice that this kind of import declaration, called dot imports, is considered bad style and might break things if the set of symbols you declare / the package you import declares changes.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论