英文:
Go: import package from the same module in the same local directory
问题
我想创建一个名为mycompany
的新包,将其发布在Github上的github.com/mycompany/mycompany-go
(类似于stripe-go或chargebee-go)。
所以我在我的MacOS上创建了一个文件夹~/Desktop/mycompany-go
。然后在该文件夹中运行go mod init github.com/mycompany/mycompany-go
。
该本地文件夹中只有以下文件:
// 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",
}
}
然而,我遇到了以下错误:
$ 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
我认为这是一个错误的建议,因为我需要使用本地版本,而不是get
远程版本。
基本上,我需要从同一文件夹、同一模块中导入一个本地包。
我该怎么办?上述代码有什么问题?
英文:
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?
答案1
得分: 2
你不能在同一个文件夹中混合使用多个包。
如果你创建一个名为mycompany
的文件夹,并将something.go
放在其中,那应该可以解决这个问题。
英文:
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
答案2
得分: 0
-- main.go --
包名和文件名要一致,Go工具默认每个目录只有一个包。在something.go中声明包名为main。
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
}
可运行示例:https://go.dev/play/p/kGBd5etzemK
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论