[英]Problems to use packages in Go
I'm having problems to use packages.我在使用包时遇到问题。 I a following literally the steps I find online, but I have an error message.
我确实按照我在网上找到的步骤进行操作,但我收到一条错误消息。
I have this package in GOPATH:我在 GOPATH 中有这个 package:
go/src/greet/day.go去/src/greet/day.go
package greet
var morning = "Good morning"
var Morning = "hey" + morning
I want to import it in my code:我想在我的代码中导入它:
go/src/app/entry.go去/src/app/entry.go
package main
import ("fmt"
"greet")
func main(){
fmt.Println(greet.Morning)
}
When I run entry.go, I receive this message: entry.go:4:3: package greet is not in GOROOT (/usr/local/go/src/greet)当我运行 entry.go 时,我收到这条消息: entry.go:4:3: package greet is not in GOROOT (/usrgo/src)
Does anybody how to fix it?有人如何解决它吗?
Thank you.谢谢你。
GOPATH isn't really used anymore. GOPATH 不再被真正使用。 You can use a different directory and run
go mod init greet
.您可以使用不同的目录并运行
go mod init greet
。 This will create a new module "greet" in that folder, and from within that module you can import packages using import "{module name}/{package path}".这将在该文件夹中创建一个新模块“greet”,您可以在该模块中使用 import“{module name}/{package path}”导入包。 It is a best practice to use the folder name as the package name, so the import path matches the folder names (except for main packages).
最佳做法是使用文件夹名称作为 package 名称,因此导入路径与文件夹名称匹配(主包除外)。
Additionally, if your module lives in a git repository, your module name should be the path to the git repository.此外,如果您的模块位于 git 存储库中,则您的模块名称应该是 git 存储库的路径。 for example,
go mod init github.com/jaenmo/myrepo
.例如,
go mod init github.com/jaenmo/myrepo
。
within your module make a folder for your main package.在您的模块中为您的主要 package 创建一个文件夹。 You should be able to import using your module name.
您应该能够使用您的模块名称进行导入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.