I can not find a way to factor out some code from main.go
into a local package when using Go modules (go version >= 1.11) outside of $GOPATH
.
I am not importing any external dependencies that need to be included into go.mod
, I am just trying to organize locally the source code of this Go module.
The file main.go
:
package main
// this import does not work
import "./stuff"
func main() {
stuff.PrintBaz()
}
The file ./stuff/bar.go
(pretending to be a local package):
package stuff
import "log"
type Bar struct {
Baz int
}
func PrintBaz() {
baz := Bar{42}
log.Printf("Bar struct: %v", baz)
}
The file go.mod
(command go mod init foo
):
module foo
go 1.12
When executing go run main.go
:
- If I
import "./stuff"
, then I see build command-line-arguments: cannot find module for path _/home/<PATH_TO>/fooprj/stuff
.
- If I
import "stuff"
, then I see build command-line-arguments: cannot load stuff: cannot find module providing package stuff
.
- If I
import stuff "./stuff"
with a package alias, then I see again: build command-line-arguments: cannot find module for path _/home/<PATH_TO>/fooprj/stuff
.
I can not find a way to make local packages work with go modules.
- What's wrong with the code above?
- How can I import local packages into other Go code inside a project defined with Go modules (file
go.mod
)?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…