Ask questionscmd/go: 'cannot find module for path' when importing from subdirectories
go version)?go version go1.11beta2 linux/amd64
Yes.
go env)?GOARCH="amd64"
GOBIN=""
GOCACHE="/home/markkuit/.cache/go-build"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/markkuit/go/"
GOPROXY=""
GORACE=""
GOROOT="/usr/local/go"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"
GCCGO="gccgo"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD="/tmp/gomodsubdirs/go.mod"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build236792179=/tmp/go-build -gno-record-gcc-switches"
The issue arises when using modules when having imports from subdirectories. I created a easy to reproduce example:
/tmp/gomodsubdirs/go.mod
module testmodule.local/gomodsubdirs
/tmp/gomodsubdirs/main.go
package main
import (
"./subdir"
"fmt"
)
func main() {
fmt.Println("Printing from main!")
subdir.Print()
}
/tmp/gomodsubdirs/subdir/subdir.go
package subdir
import "fmt"
func Print() {
fmt.Println("Printing from subdir!")
}
I expected build to be successful both with and without modules, but it looks like putting code in subdirectories is troublesome for go modules (or I'm doing something wrong). I tend to do this quite a lot when I have a package in a subdirectory with a lot of files (mostly boilerplate code), which isn't however worthy of being a separate package itself or is too strictly related to the main package to be put apart from it. Note that I tried having a go.mod inside the subdirectory as well (both empty and filled), but it made no difference.
> go build main.go
build .: cannot find module for path _/tmp/gomodsubdirs/subdir
> env GO111MODULE=off go build main.go
> ./main
Printing from main!
Printing from subdir!
Answer
questions
figiel
Hi @rsc,
In modules, there finally is a name for the subdirectory. If the parent directory says "module m" then the subdirectory is imported as "m/subdir", no longer "./subdir".
Is this something which should work now or is it going to be added? I can't get this to work with go 1.12:
~/tmp$ tree topdir/
topdir/
├── go.mod
├── subdir
│ └── subdir.go
└── topdir.go
1 directory, 3 files
~/tmp$ cat topdir/go.mod
module example.com/topdir
go 1.12
~/tmp$ cat topdir/topdir.go
package topdir
import "topdir/subdir"
type Topdir subdir.Subdir
~/tmp$ cat topdir/subdir/subdir.go
package subdir
type Subdir interface{}
~/tmp$ cd topdir/
~/tmp/topdir$ go build
topdir.go:3:8: unknown import path "topdir/subdir": cannot find module providing package topdir/subdir
Related questions