Reference a symbol in a Go package without knowing if you are in that package?

520 views Asked by At

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

There are 1 answers

8
fuz On

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.