Understanding Internal Packages
Internal packages, denoted by the "internal" directory, are intended for grouping related code that should not be exposed outside the project. In Go modules, internal packages cannot be imported by external projects.
Module Structure
In the provided example, the project structure is as follows:
project/ internal/ foo/ foo.go # package foo bar/ bar.go # package bar main.go
where main.go imports the internal packages project/internal/foo and project/internal/bar.
Import Issue
The issue you encountered was trying to import internal packages from outside the project directory. Internal packages can only be imported from within the same project, so using the paths project/internal/foo and project/internal/bar from main.go would not work.
Solution with Go Modules
However, with the introduction of Go modules in Go v1.11, it's no longer necessary to specify your project path in $GOPATH/src. Create a go.mod file and define the internal package modules as follows:
project/ go.mod main.go \---internal +---bar | bar.go | go.mod | \---foo foo.go go.mod
project/internal/bar/go.mod
module bar go 1.14
project/internal/bar/bar.go
package bar import "fmt" // Bar prints "Hello from Bar" func Bar() { fmt.Println("Hello from Bar") }
project/internal/foo/go.mod
module foo go 1.14
project/internal/foo/foo.go
package foo import "fmt" // Foo prints "Hello from Foo" func Foo() { fmt.Println("Hello from Foo") }
project/main.go
package main import ( "internal/bar" "internal/foo" ) func main() { bar.Bar() foo.Foo() }
project/go.mod
module project go 1.14 require internal/bar v1.0.0 replace internal/bar => ./internal/bar require internal/foo v1.0.0 replace internal/foo => ./internal/foo
Key Points
The above is the detailed content of How Do Go Modules Handle Internal Packages to Prevent External Imports?. For more information, please follow other related articles on the PHP Chinese website!