登录
首页 >  Golang >  Go问答

为什么我的Golang包函数没有被我的测试识别?

来源:stackoverflow

时间:2024-03-17 17:27:29 124浏览 收藏

在 Go 语言中,子目录中包的导入路径由模块路径和子目录路径组成。模块路径通常在 go.mod 文件中指定。当子目录中的包未被测试识别时,可能是因为模块路径设置不当或包导入路径不正确。解决方法包括将包移动到模块路径所在目录或将包导入为模块路径和子目录路径的组合。

问题内容

我在 gopath 之外有一个目录(我正在努力理解 go 模块;这还不是一个模块,只是其中的一个步骤)。

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

树看起来像:

你好/(包主)

  • 你好。
  • hello_test.go
  • morestrings/(包morestrings)
    • 反向.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

我正在遵循此处和此处所示的设置/结构。

go版本是1.14.2 darwin/amd64

go111module 设置为 autogo111module=auto(如果有任何轴承)。

我尝试重新加载 vs code 窗口。

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

有效的方法是将 morestrings 目录上移一个级别,以便与 hello 位于同一目录中:~/development/golang/understanding-modules/morestrings

但是教程使它看起来像 ~/development/golang/understanding-modules/hello/morestrings 应该可以工作。

我错过了什么?


解决方案


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

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

在本例中,您的模块路径是 ~/Development/golang/understanding-modules

所以任何包都必须与那里相关。如果你想将它移到其他地方,你需要给它自己的模块路径。否则那一定是它所在的地方。或者必须将其作为包 hello/morestrings 导入。

理论要掌握,实操不能落!以上关于《为什么我的Golang包函数没有被我的测试识别?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>