英文:
How to go mod get local package?
问题
我想让go.mod获取selfCheck文件夹内的包(获取selfCheck文件夹内的包)。
selfCheck/encrypt,selfCheck/searchSchool
我的截图在这里
(不要在意vendor文件,我会将其删除。)
英文:
I want go.mod get a folder inside the selfCheck(get package inside selfCheck folder).
selfCheck/encrypt , selfCheck/searchSchool
my screenshots is here
(don't mind vendor file. i'll remove it.)
答案1
得分: 0
你不需要在go.mod文件中要求项目本身的文件夹。go.mod
只需要从其他存储库中要求外部包。
我写了一篇关于如何开始使用Go的博文,其中涵盖了这个问题。https://marcofranssen.nl/start-on-your-first-golang-project
我还写了很多关于Go的文章。https://marcofranssen.nl/categories/golang
总结一下,你应该使用你的git存储库的完整URL,这样其他项目可以将其作为最佳实践依赖。
例如:
go mod init github.com/your-user/selfcheck
一旦你这样做了,你的go.mod
文件看起来像这样。
module github.com/your-user/selfcheck
go 1.17
请注意,驼峰命名法不是命名go包的方式。Go包应该全部小写。
现在,如果你想创建子包,你应该创建文件夹。例如,你的项目可能如下所示。
$ tree selfcheck
selfcheck
├── go.mod
├── main.go
└── searchschool
└── searchschool.go
1 directory, 3 files
现在,要引用searchschool
包中的代码,你可以在main.go
中进行如下操作。
package main
require (
"fmt"
"github.com/your-user/selfcheck/searchschool"
)
func main() {
fmt.Println(searchschool.Execute())
}
请注意,所有函数都必须以大写字母开头,以便在searchschool包之外访问它们。例如,searchschool/searchschool.go
中的函数。
package searchschool
func Execute() string {
return privateFunc() + "!"
}
func privateFunc() string {
return "Hello World"
}
英文:
You don't need to require a folder in the project itself in go.mod files. go.mod
is only requireing external packages from other repositories.
I wrote a blogpost on starting with Go that covers this question. https://marcofranssen.nl/start-on-your-first-golang-project
I also wrote a whole bunch more articles on Go https://marcofranssen.nl/categories/golang
In summary what you should do it use the full url of your git repository so other projects can depend on it as a best practice.
e.g.
go mod init github.com/your-user/selfcheck
Once you did that your go.mod
file looks like this.
module github.com/your-user/selfcheck
go 1.17
Please note camel casing is not the way you name go packages. Go packages should be all lowercase.
Now if you want to create sub packages as you are asking for you should create folders. e.g. your project could look like this.
$ tree selfcheck
selfcheck
├── go.mod
├── main.go
└── searchschool
└── searchschool.go
1 directory, 3 files
Now to reference code from the searchschool
package you can do the following in main.go
.
package main
require (
"fmt"
"github.com/your-user/selfcheck/searchschool"
)
func main() {
fmt.Println(searchschool.Excute())
}
Please note all functions have to start with an uppercase to access them outside of the searchschool package. E.g. searchschool/searchschool.go
package searchschool
func Execute() string {
return privateFunc() + "!"
}
func privateFunc() string {
return "Hello World"
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论