我正在学习教程并坚持这一点。我也尝试查看官方文档,但无法发现这是错误的。
在这里发帖之前,我发现 GOPATH 也需要配置。
GOPATH: A:\GO
utils 文件夹路径:A:\GO\fem-intro-to-go\05_toolkit\code\utils
utils 中有 2 个文件,math.go和add_test.go。
数学
package utils
import "fmt"
func printNum(num int) {
fmt.Println("Current Number:", num)
}
// Add adds together multiple numbers
func Add(nums ...int) int {
total := 0
for _, v := range nums {
printNum(v)
total += v
}
return total
}
add_test.go
package utils
import "testing"
func TestAdd(t *testing.T) {
expected := 4
actual := Add(2, 2)
if actual != expected {
t.Errorf("Add function does not add up: Expected: %d, Actual: %d", expected, actual)
}
}
VS 代码在 add_test.go 中出现错误:未声明的名称:添加
错误的完整描述:
{
"resource": "/a:/GO/fem-intro-to-go/05_toolkit/code/utils/add_test.go",
"owner": "_generated_diagnostic_collection_name_#1",
"code": {
"value": "UndeclaredName",
"target": {
"$mid": 1,
"external": "https://pkg.go.dev/golang.org/x/tools/internal/typesinternal?utm_source%3Dgopls#UndeclaredName",
"path": "/golang.org/x/tools/internal/typesinternal",
"scheme": "https",
"authority": "pkg.go.dev",
"query": "utm_source=gopls",
"fragment": "UndeclaredName"
}
},
"severity": 8,
"message": "undeclared name: Add",
"source": "compiler",
"startLineNumber": 9,
"startColumn": 12,
"endLineNumber": 9,
"endColumn": 15
}
使用 go 1.16.6 构建代码时,我没有发现您的代码有任何问题。如果我开始一个新的 go 项目:
mkdir example
cd example
go mod init example
然后将您的代码放在utils/
目录中,并将以下内容放入main.go
:
package main
import (
"example/utils"
"fmt"
)
func main() {
answer := utils.Add(1, 2, 3)
fmt.Printf("got answer: %d\n", answer)
}
所以我有以下布局:
$ tree .
.
├── example
├── go.mod
├── main.go
└── utils
├── add_test.go
└── math.go
您的代码编译时出现问题:
$ go build
我运行生成的二进制文件:
$ ./example
Current Number: 1
Current Number: 2
Current Number: 3
got answer: 6
我想指出的是,我还没有设置GOPATH
或任何其他GO*
环境变量来使其工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句