A technical article about Go package management

Purpose: Previously, I wanted to reference another project I wrote within a Go project, but got stuck for hours and even considered giving up.

1 Creating Projects

We create a directory called gogogo, which contains two projects:

Create main.go files separately

utils/main.go

1
2
3
4
5
6
7
8
package utils

import "fmt"

// Uppercase functions can be accessed externally
func Log(){
fmt.Print("go mod is shit")
}

demo/main.go

1
2
3
4
5
6
7
8
9
package main
import (
"fmt"
"utils" // This is our other project
)
func main() {
fmt.Print("hello\n")
utils.Log() // Call method from the other project
}

2 Initialize each project (using go mod init project_name)

1
2
3
cd demo 
go mod init demo
go mod tidy

1
2
3
cd utils
go mod init utils
go mod tidy

At this point, the code structure looks like this, with go.mod auto-generated:

!!!Note: If the project name you use with init contains Go keywords or reserved names, it will fail!!!

错误示范

3 The Key Step: Modify go.mod

Use the replace directive to specify the directory corresponding to the imported package:

Then run: go mod tidy (This command lets Go handle dependencies; if there are remote dependencies, they will be
downloaded automatically.)
As a result, you might notice that go.mod has changed slightly!

4 Running the Go Code

Option 1: Run directly using go run

1
go run main.go

Option 2: Build an executable and run it

1
2
3
go build
# After building, an executable file named after the project will be generated
./demo


本站总访问量