問題:在使用go mod后,執行編譯會報錯:
Cannot load xxx: cannot find module providing package xxx
目錄結構如下: J:. │ └─src | ├─day1 | | | | | ---goroute.go | └─main | |--main.go | ---go.mod # cat go.mod module mytest go 1.12 ============================
解決辦法:
============================ 在go.mod文件中首行指定了模塊名:mytest, 那么: 1. 在main.go文件中導入自定義模塊day1時,自定義模塊名前要加模塊名前綴mytest: 例如: import (
"mytest/src/day1"
) 2. 在編譯go文件時,也要添加模塊名前綴: 例如: 在項目根目錄下,執行編譯: go build mytest/src/main
運行:
go run mytest/src/main
附:
相關代碼
goroute.go
package day1 import "fmt" func Gomy(a int) { fmt.Println("output: ", a) }
main.go
package main import ( "mytest/src/day1" "time" ) func main() { for i := 0; i < 100; i++ { go day1.Gomy(i) } time.Sleep(time.Second) }