我正在按照教程(https://golang.org/doc/tutorial/getting-started)开始使用Go,但是我已经遇到了问题。当我运行以下代码时:
package main
import "fmt"
import "rsc.io/quote"
func main() {
fmt.Println(quote.Go())
}
我在控制台中收到以下错误消息:
C:\Users\myname\Documents\Work\GO\hello>go run hello.go
hello.go:7:8: cannot find package "rsc.io/quote" in any of:
C:\Program Files\Go\src\rsc.io\quote (from $GOROOT)
C:\Users\myname\go\src\rsc.io\quote (from $GOPATH)
我猜这是我安装Go的方式/位置的问题,有人可以请问一下吗?
谢谢
答案 0 :(得分:8)
具有模块支持的go
工具会自动下载并安装依赖项。但是要使其正常工作,您必须初始化模块。
仅将源保存在.go
文件中并与go run hello.go
一起运行是不够的,go.mod
文件必须存在。
要初始化模块,请按照本教程中的指示进行操作:
go mod init hello
输出应为:
go: creating new go.mod: module hello
所以下次运行
go run hello.go
将自动下载rsc.io/quote
软件包:
go: finding module for package rsc.io/quote
go: found rsc.io/quote in rsc.io/quote v1.5.2
Don't communicate by sharing memory, share memory by communicating.
最后一行是成功运行应用程序的输出。
答案 1 :(得分:0)
2021/6/3 go 版本 go1.16.4 linux/amd64
root@zqf-vm:/workspace/go_workspace/hello# go mod init hello
go: creating new go.mod: module hello
go: to add module requirements and sums:
go mod tidy
root@zqf-vm:/workspace/go_workspace/hello# go run hello.go
hello.go:6:2: no required module provides package rsc.io/quote; to add it:
go get rsc.io/quote
root@zqf-vm:/workspace/go_workspace/hello# go mod init hello
go: /workspace/go_workspace/hello/go.mod already exists
root@zqf-vm:/workspace/go_workspace/hello# go run hello.go
hello.go:6:2: no required module provides package rsc.io/quote; to add it:
go get rsc.io/quote
root@zqf-vm:/workspace/go_workspace/hello# go mod tidy
go: finding module for package rsc.io/quote
go: downloading rsc.io/quote v1.5.2
go: found rsc.io/quote in rsc.io/quote v1.5.2
go: downloading rsc.io/sampler v1.3.0
go: downloading golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c
root@zqf-vm:/workspace/go_workspace/hello# go run hello.go
Don't communicate by sharing memory, share memory by communicating.