起因
在看菜鸟教程的时候遇到包相关的问题
代码
// helloworld.go
package main
import (
"fmt"
"./myMath"
)
func main(){
fmt.Println("Hello World!")
fmt.Println(mathClass.Add(1,1))
fmt.Println(mathClass.Sub(1,1))
}
// myMath1.go
package mathClass
func Add(x,y int) int {
return x + y
}
// myMath2.go
package mathClass
func Sub(x,y int) int {
return x - y
}
文件结构
package_addsub
--helloworld.go
myMath
--myMath1.go
--myMath2.go
问题
PS C:\Users\LOUHOIN\Desktop\UserName\GoCode\package_addsub> go run helloworld.go
helloworld.go:5:2: "./myMath" is relative, but relative import paths are not supported in module mode
解决方法
引入go.mod来使用自定义包
文件结构
package_addsub
--helloworld.go
--go.mod
myMath
--myMath1.go
--myMath2.go
// helloworld.go
module package_addsub
go 1.20
修改helloworld.go的import部分
// helloworld.go
package main
import (
"fmt"
mathClass "package_addsub/myMath"
)
func main() {
fmt.Println("Hello World!")
fmt.Println(mathClass.Add(1, 1))
fmt.Println(mathClass.Sub(1, 1))
}
再次运行,顺利解决
PS C:\Users\LOUHOIN\Desktop\UserName\GoCode\package_addsub> go run helloworld.go
Hello World!
2
0
相关链接