Sometimes you just want to be able to modularize/namespace your code without having to make a full-fledged library out of it.
Go seems to discourage this sort of this as of 1.16 and wants you make a separate remote repo to house such code,
and then you can import it into your main project.
Unless I'm missing something, this feels like Go discourages local namespacing of code within a single project.
But there is a way to accomplish this even if it's not considered idiomatic.
- Relative to the root directory of your project, first create a new directory within your main project to house a local module, in this example
zomg. - Then from within that directory create a new file, say,
zomg.go, and put the following in it:
package zomg
import "fmt"
func Hello() {
fmt.Println("Hello, local module user!!!")
}
- Remaining in that directory, run
go mod init zomgto create a newgo.modfile which should look like this:
module zomg
go 1.16
- In the projects main directory, create a new
main.gofile with the following:
package main
import "zomg"
func main() {
zomg.Hello()
}
- From the project root, run
go mod init mainto produce this initial file:
module main
go 1.16
- Next, edit
go.modand add a line to reference the submodule like this:
module main
go 1.16
replace zomg => ./zomg
- At this point if you try running
go run main.go, you should see the following error:
main.go:3:8: module zomg provides package zomg and is replaced but not required; to add it:
go get zomg
- Run
go get zomgand you should see that the topmostgo.modshould look like this:
module main
go 1.16
replace zomg => ./zomg
require zomg v0.0.0-00010101000000-000000000000 // indirect
- Now run
go run main.goand you should see the following:
Hello, local module user!!!