sadlil
sadlil

Reputation: 3163

Golang, Using a Structure or function of a main package from a sub package

I am trying to write a go project with several sub projects. For an simple example the project looks like this

Main
 |- package one
    |- package one.one
    |- package one.two
 |- package two

From my main package i can use any function or structure of any sub package By importing them. But My question is how can i access an struct or function of main from any sub package.

Upvotes: 4

Views: 5233

Answers (2)

Bozhidar Atanasov
Bozhidar Atanasov

Reputation: 81

One way to do this, for me, is to "inject" a value in the package. It feels like a hacky way to do it, since you gotta explicitly call a function in main, but it works:

package oneone

var(
    x string
)

//x is copied here, we can also pass a pointer if original value is needed
func RegisterX(outsideX string) {
    x = outsideX
}

------
package main
func main() {
    ...
    x := "outside X"
    oneone.RegisterX(x)
}

Upvotes: 0

Volker
Volker

Reputation: 42432

By importing the "subpackages" in main. But do not produce an import cycle (Restructure your code in this case).

Note that Go has (almost*) no notion of _sub_package: These are all plain packages and the directory layout has no influence on imports and usability/accessability of exported functions, types, methods, fields, variables and constants.

*) Internal packages and vendored packages depend on directory layout.

Upvotes: 6

Related Questions