Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Mutual" package import in Golang

Tags:

import

package

go

Is it possible to do something like a "mutual" package import in Golang?

Lets say for example I have two packages, A and B with functions AFunc and BFunc, BFunc2

package A
import "B"

func AFunc() {
    //do stuff but also use
    B.BFunc()
}

-

package B
import "A"

func BFunc() {
    //do foo
}

func BFunc2() {
    //do different stuff but also use
    A.AFunc()
}

Is there a way to achieve this without using a third package as "bridge"?

Edit: To clarify the question a bit, this is of course not possible by "simply doing" it since the compiler will throw an import cycle not allowed error. The question is, is there a cleaner or more established way of working around this problem then building a "bridge package"?

like image 797
cynexit Avatar asked Jul 02 '14 08:07

cynexit


1 Answers

interface should be an obvious answer: as long as both packages propose interfaces with a common set of functions, it allows for:

  • packageB to use functions from A (import A)
  • packageA to call functions from B without having to import B: all it need to be passed B instances which implements an interface defined in A: those instances will be views as A object.
    In that sense, packageA ignores the existence of packageB.

This is also illustrated in the comment of "Cyclic dependencies and interfaces in golang".

If package X accepts/stores/calls methods on/returns types defined package Y, but doesn't actually access Y's (non-method) functions or variables directly, X can use an interface that the type in Y satisfies rather than actually importing Y.

avoiding dependencies with interfaces in general, you can see how, say, the io module doesn't depend on os for the File class even though its functions can work on Files. (It just defines io.Writer, etc., and *os.File satisfies those interfaces.)

For instance, io accepts a 'Writer' in its Copy() function (which can be a File or another else knowing how to write), and ignores completely os(.File)

like image 124
VonC Avatar answered Nov 15 '22 07:11

VonC