为什么我的测试无法识别我的Golang软件包功能?

问题描述

我的GOPATH位于目录(我正在研究Go模块;这还不是一个模块,只是前进的一步)。

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

这棵树看起来像:
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设置为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。