在Go中使用包时遇到的问题

huangapple go评论71阅读模式
英文:

Problems to use packages in Go

问题

我遇到了使用包的问题。我按照网上找到的步骤进行操作,但是出现了错误信息。

我在GOPATH中有这个包:

go/src/greet/day.go

package greet

var morning = "早上好"
var Morning = "嘿" + morning

我想在我的代码中导入它:

go/src/app/entry.go

package main

import (
	"fmt"
	"greet"
)

func main(){
	fmt.Println(greet.Morning)
}

当我运行entry.go时,我收到以下消息:
entry.go:4:3: package greet is not in GOROOT (/usr/local/go/src/greet)

有人知道如何修复吗?

谢谢。

英文:

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:

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

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)

Does anybody how to fix it?

Thank you.

答案1

得分: 1

GOPATH不再真正使用。您可以使用不同的目录并运行go mod init greet。这将在该文件夹中创建一个名为"greet"的新模块,并且在该模块内部,您可以使用import "{模块名称}/{包路径}"来导入包。最佳实践是使用文件夹名称作为包名称,以便导入路径与文件夹名称匹配(除了主包)。

此外,如果您的模块位于git存储库中,则模块名称应该是git存储库的路径。例如,go mod init github.com/jaenmo/myrepo

在您的模块中创建一个文件夹用于主包。您应该能够使用您的模块名称进行导入。

英文:

GOPATH isn't really used anymore. You can use a different directory and run 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}". 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).

Additionally, if your module lives in a git repository, your module name should be the path to the git repository. for example, go mod init github.com/jaenmo/myrepo.

within your module make a folder for your main package. You should be able to import using your module name.

huangapple
  • 本文由 发表于 2022年8月29日 00:02:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/73520194.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定