A package is a collection of source files in the same directory that are compiled together. A module is a collection of related Go packages that are released together.
go mod init <module_name>
- If you want to use your module from other module. You can set
github.com/<github user/org name>/<github repo name>
to your module name. - This command will generate a go.mod file.
Example:
go mod init github.com/nakamasato/kubernetes-operator-basics/05-golang-basics/02-package-and-module
go: creating new go.mod: module github.com/nakamasato/kubernetes-operator-basics/05-golang-basics/02-package-and-module
I specified the path to the current directory.
go.mod
file will be created.
module github.com/nakamasato/kubernetes-operator-basics/05-golang-basics/02-module
go 1.19
-
Create a
main.go
.package main import "fmt" func main() { fmt.Println("Hello, World") }
-
Run
main.go
go run main.go Hello, World
- Add
mypackage
. Create amypackage/mypackage.go
package mypackage func GetName() string { return "MyName" }
- Use
mypackage
in the module.- Import the pacakge in
main.go
import ( "fmt" // Packages in the standard library do not have a module path prefix "<module_name>/mypackage" // e.g. "github.com/nakamasato/kubernetes-operator-basics/05-golang-basics/02-module/mypackage" )
- Standard library: https://pkg.go.dev/std
- Use
GetName
function inmypackage
package.func main() { name := mypackage.GetName() fmt.Printf("Hello, %s\n", name) }
- Import the pacakge in
- Run
main.go
go run main.go Hello, MyName
-
Import a package
import "github.com/google/go-github/v47/github"
-
Use it.
client := github.NewClient(nil) // list all organizations for user "willnorris" orgs, _, err := client.Organizations.List(context.Background(), "willnorris", nil) if err != nil { fmt.Println("Error") os.Exit(1) } for i, org := range orgs { fmt.Println(i, *org.Login) }
-
Run
go mod tidy
go.mod
is updated:require github.com/google/go-github/v47 v47.1.0 require ( github.com/google/go-querystring v1.1.0 // indirect golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 // indirect )
-
Run main.go
go run main.go
Hello, MyName 0 diso 1 activitystreams 2 indieweb 3 webfinger 4 todogroup 5 maintainers 6 perkeep 7 tailscale
- Packages, variables, and functions.
- Flow control statements: for, if, else, switch and defer