go mod 和 workspace
引入本地包
.
├── go.mod
├── main.go
└── stringutils
└── concat.go
1 directory, 3 files
go.mod
module test
go 1.20
main.go
package main
import (
"fmt"
"test/stringutils"
)
func main() {
fmt.Println(stringutils.Concat("qianjin", "yike"))
}
stringutils/concat.go
package stringutils
func Concat(s1 string, s2 string) string {
return s1 + s2
}
引入外部的包(workspace)
.
├── go.work
├── hello
│ ├── go.mod
│ ├── go.sum
│ └── main.go
└── test4
├── go.mod
└── double.go
2 directories, 6 files
go.work
go 1.20
use (
./hello
./test4
)
hello/go.mod
module example.com/hello
go 1.20
require github.com/leonzai/test4 v0.0.0-20230427075924-03b461cd6f36
hello/main.go
package main
import (
"fmt"
"github.com/leonzai/test4"
)
func main() {
fmt.Println(test4.Double("ab"))
}
test4/go.mod
module github.com/leonzai/test4
go 1.20
test4/double.go
package test4
func Double(s string) string {
return s + s
}
注意:这里在 go.work 同级目录下和 hello 目录下运行 go run example.com/hello 都只会加载本地的 test4 不会加载远程的 github.com/leonzai/test4 (即使你 go get 更新了它的版本也不会加载)。