I want to create new package mycompany
that will be published on Github at github.com/mycompany/mycompany-go
(something similar to stripe-go or chargebee-go for example).
So I have created a folder ~/Desktop/mycompany-go
on my MacOS. Then inside that folder I run go mod init github.com/mycompany/mycompany-go
.
I have only these files in that local folder:
// go.mod
module github.com/mycompany/mycompany-go
go 1.19
// something.go
package mycompany
type Something struct {
Title string
}
// main.go
package main
import (
"github.com/mycompany/mycompany-go/mycompany"
)
func main() {
s := mycompany.Something {
Title: "Example",
}
}
However I get this error:
$ go run main.go
main.go:4:3: no required module provides package github.com/mycompany/mycompany-go/mycompany; to add it:
go get github.com/mycompany/mycompany-go/mycompany
I think that this is a wrong suggestion, because I need to use the local version, in the local folder, not get
a remote version.
Basically I need to import a local package, from the same folder, from the same module.
What should I do? What's wrong with the above code?
CodePudding user response:
You can't mix multiple packages in the same folder.
If you create a folder mycompany
and put something.go
inside it, that should fix the problem
CodePudding user response:
The Go tool assumes one package per directory. Declare the package as main in something.go.
-- main.go --
package main
import "fmt"
func main() {
s := Something{
Title: "Example",
}
fmt.Println(s)
}
-- go.mod --
module github.com/mycompany/mycompany-go
go 1.19
-- something.go --
package main
type Something struct {
Title string
}
Runnable example: https://go.dev/play/p/kGBd5etzemK