Why is my Golang package function not recognized by my test?

5k views Asked by At

I have a directory outside of my GOPATH (I'm working on understanding Go modules; this is not yet a module, just a step along the way).

The directory path is ~/Development/golang/understanding-modules/hello.

The tree looks like:
hello/ (package main)

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

My function in reverse.go is:

// 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)
}

My test function in reverse_test.go is:

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)
    }
}

The ReverseRunes function is showing the error undeclared name: ReverseRunes.

I'm following the set up/structure shown here & here.

Go version is 1.14.2 darwin/amd64

GO111MODULE is set to auto: GO111MODULE=auto, if that has any bearing.

I have tried reloading the VS Code window.

I have tried deleting the hello.go & hello_test.go files.

What does work is moving the morestrings directory up a level so that is in the same directory as hello: ~/Development/golang/understanding-modules/morestrings.

But the tutorials make it seem like ~/Development/golang/understanding-modules/hello/morestrings should work.

What am I missing?

1

There are 1 answers

10
Sean F On

Packages in subdirectories have import paths consisting of the module path plus the path to the subdirectory.

The module path is specified in the go.mod file.

In this case your module path is ~/Development/golang/understanding-modules

So any package must be relative to there. If you want to move it elsewhere you need to give it its own module path. Otherwise that is where it must be. Or it must be imported as package hello/morestrings.