多包go模块中的名称解析问题

I'm trying to create a module that contains multiple packages but I don't understand why I'm getting errors.

Layout:

λ ~/code/go-test/src/mod-test/ » tree
.
├── cmd
│   └── a.go
├── go.mod
├── main.go
└── pkg
    └── foo
        └── b.go

3 directories, 4 files

main.go:

package main

import (
        "fmt"
        "github.com/go-test/mod-test/cmd"
)

func main() {
        fmt.Println("main")
        A()
}

cmd/a.go:

package cmd

import (
        "fmt"
        "github.com/go-test/mod-test/pkg/foo"
)

func A() {
        fmt.Println("a")
        B()
}

pkg/foo/b.go:

package foo

import "fmt"

func B() {
        fmt.Println("B")
}

go.mod:

module github.com/go-test/mod-test

go 1.12

I get the following error:

λ ~/code/go-test/src/mod-test/ » go build
# github.com/go-test/mod-test/cmd
cmd/a.go:5:2: imported and not used: "github.com/go-test/mod-test/pkg/foo"
cmd/a.go:10:2: undefined: B

Can anyone help explain what I've done wrong and why I get the error?

Thanks,

There is bug in the cmd/a.go. You did not use "github.com/go-test/mod-test/pkg/foo". Also B() is under github.com/go-test/mod-test/pkg/foo package, so you have to specify it. See below:

package cmd

import (
        "fmt"
        "github.com/go-test/mod-test/pkg/foo"
)

func A() {
        fmt.Println("a")
        // B()
        foo.B()
}

There is another way to avoid this. If you don't want to use the package name, simply just put a . before importing a package. By doing that you can call a public fn or use a public var of that package. After doing that your main.go and cmd/a.go files look like below:

main.go:

package main

import (
        "fmt"
        . "github.com/go-test/mod-test/cmd"
)

func main() {
        fmt.Println("main")
        A()
}

cmd/a.go:

package cmd

import (
        "fmt"
        . "github.com/go-test/mod-test/pkg/foo"
)

func A() {
        fmt.Println("a")
        B()
}