在不知道是否在Go包中的情况下引用Go包中的符号?

huangapple go评论73阅读模式
英文:

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 the pkg.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" as bar.S as opposed to the expected foo.S.

The following things could be used to work around this:

  • In the package "foo", create an internal object foo whose members are the symbols foo exports. This allows you to use the foo.S syntax in foo itself, but is a horrible kludge.

  • Use an import declaration like

      import . "foo"
    

    which allows you to use symbol S from package "foo" as S, 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.

huangapple
  • 本文由 发表于 2014年11月18日 07:06:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/26983669.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定