【问题标题】:Why is my Golang package function not recognized by my test?为什么我的测试无法识别我的 Golang 包功能?
【发布时间】:2021-01-11 07:30:02
【问题描述】:

我在我的 GOPATH 之外有一个目录(我正在努力理解 Go 模块;这还不是一个模块,只是前进的一步)。

目录路径为~/Development/golang/understanding-modules/hello

这棵树看起来像:
你好/(主包)

  • hello.go
  • hello_test.go
  • morestrings/(包morestrings)
    • reverse.go
    • reverse_test.go

我在reverse.go的功能是:

// Package morestrings implements additional functions to manipulate UTF-8
// encoded strings, beyond what is provided in the standard "strings" package.
package morestrings

// ReverseRunes returns its argument string reversed rune-wise left to right.
func ReverseRunes(s string) string {
    r := []rune(s)
    for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
        r[i], r[j] = r[j], r[i]
    }
    return string(r)
}

我在reverse_test.go的测试函数是:

package morestrings

import "testing"

func TestReverseRunes(t *testing.T) {
    got := ReverseRunes("Hello, World!")
    want := "!dlroW ,olleH"
    if got != want {
        t.Logf("Wanted %s, but got %s", want, got)
    }
}

ReverseRunes 函数显示错误undeclared name: ReverseRunes

我遵循herehere 显示的设置/结构。

Go 版本是1.14.2 darwin/amd64

GO111MODULE 设置为 auto: GO111MODULE=auto,如果有任何影响的话。

我已尝试重新加载 VS Code 窗口。

我已尝试删除 hello.gohello_test.go 文件。

起作用是将morestrings 目录向上移动一个级别,使其与hello 位于同一目录中:~/Development/golang/understanding-modules/morestrings

但是这些教程让~/Development/golang/understanding-modules/hello/morestrings 看起来应该可以工作。

我错过了什么?

【问题讨论】:

  • 阅读如何编写 Go 代码并坚持下去。并且:显示您在命令行中使用的文字命令和逐字输出。
  • 如果你想尝试模块,你不能跳过模块初始化步骤。
  • 如果它在你的 GOPATH 之外,它必须是一个模块。他们之间没有“台阶”。只需运行go mod init
  • @Adrian,错误显示在 VS Code 中,而不是终端中。在遵循如何编写 Go 代码时,我一直无法让事情正常工作,所以我尝试备份以查看我是否遗漏了其他内容,并查看了许多其他材料试图找出答案。谢谢!

标签: go go-modules go-packages


【解决方案1】:

子目录中的包的导入路径由模块路径加上子目录的路径组成。

模块路径在 go.mod 文件中指定。

在这种情况下,您的模块路径是 ~/Development/golang/understanding-modules

所以任何包都必须是相对于那里的。如果你想把它移到别处,你需要给它自己的模块路径。否则那就是它必须在的地方。或者它必须作为包 hello/morestrings 导入。

【讨论】:

  • 考虑到“模块路径是在 go.mod 文件中指定的”,考虑到 go.mod 的内容没有给出,你怎么能声称知道模块路径(因为,事实上,没有)?
  • 你怎么能说没有?
  • 因为他们给出了文件结构并且它不包含 go.mod,并且因为他们明确表示“这还不是一个模块”。
  • 不,他们提供了一份源文件列表,并没有说明它是否包含所有内容。 “还不是模块”这句话很明显,这就是为什么他们在堆栈溢出时问“为什么不呢?”。所以你离谱而且不正确。
  • 即使它 一个模块,尽管有所有相反的证据,他们仍然没有从他们的 go.mod 中提供导入路径,所以你的回答说“你的模块路径是 ~/Development/golang/understanding-modules” 是基于任何假设。导入路径不是文件系统路径,它是模块中定义的任何内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多