Home >Backend Development >Golang >How to Effectively Organize Go Code Using Internal Packages with Modules?
Question:
How do I effectively organize Go code using "internal" packages?
Initial Problem:
Despite placing the project outside the GOPATH, importing internal packages from main.go fails, unless the relative path is used (e.g., "./internal/foo|bar").
Introduction of Modules:
With the introduction of modules in Go v1.11 and above, placing the project inside $GOPATH/src is no longer necessary. Instead, you need to create a go.mod file to specify the location of each module.
Example:
Consider the following project structure:
project/ go.mod main.go internal/ bar/ bar.go go.mod foo/ foo.go go.mod
go.mod Files:
The go.mod files for the internal packages are simple:
module bar go 1.14
module foo go 1.14
Code in Internal Packages:
// bar.go package bar import "fmt" // Bar prints "Hello from Bar" func Bar() { fmt.Println("Hello from Bar") } // foo.go package foo import "fmt" // Foo prints "Hello from Foo" func Foo() { fmt.Println("Hello from Foo") }
main.go:
// main.go package main import ( "internal/bar" "internal/foo" ) func main() { bar.Bar() foo.Foo() }
Project go.mod File:
The project go.mod file informs Go about the internal packages and their locations:
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
Important Notes:
Execution:
Running the main.go file will now print:
Hello from Bar Hello from Foo
This example demonstrates how to effectively use internal packages within a Go project using modules.
The above is the detailed content of How to Effectively Organize Go Code Using Internal Packages with Modules?. For more information, please follow other related articles on the PHP Chinese website!