我是 Go 的新手,但我来自 C++ 学校。我只是想做一个项目,把逻辑拆分成多个文件。
在 C++ 中,我只需要将我的 main_file.cpp
放在一个
#include "my_own_lib.hpp"
(类似于 Node.js 中的 module.exports
和 require('relative/path/to/my-own-lib')
)
就是这样。在 Go 中,我遵循相同的逻辑,但我的结果是:
$ go run main.go
main.go:4:8: open /Users/mt/Documents/Codes/go/src/github.com/mt/Apollo/tst: no such file or directory
我的文件:
main.go
package main
import "fmt"
import "./tst"
func main() {
fmt.Println("just testing")
tst.p()
}
tst.go
package tst
import "fmt"
func p() {
fmt.Println("ola")
}
当然我的文件结构是:
myFolder/
|- main.go
|_ tst.go
谁能告诉我这样做的正确方法是什么?
最佳答案
如果您也将 tst.go 的包设置为“package main”,您将能够在没有任何导入语句的情况下访问 p()。
$ cat main.go
package main
func main() {
p()
}
$ cat tst.go
package main
import "fmt"
func p() {
fmt.Println("ola")
}
$ go build ./ && ./test
ola
我相信这会满足您的要求:
I just want to make a project and split the logic into many different files.
如果你正在构建一个程序而不是一个库,公认的 Go 约定是将你的所有文件作为“package main”:
The package “main” tells the Go compiler that the package should compile as an executable program instead of a shared library. http://thenewstack.io/understanding-golang-packages/
请解释您的反对意见
这里有一些著名的 Go 项目的例子,它们完全按照我说的做:
这些是代码拆分在多个 Go 文件中的可执行文件,所有这些文件都属于“package main”。
看到OP有点不清楚,你可以选择解释为他要创建一个外部包,tst。但他说得很清楚:
I just want to make a project and split the logic into many different files.
他说很多文件 - 不是很多外部包。他还说:
of course my file structure is:
myFolder/
|- main.go
|_ tst.go
我的建议是在这种情况下做事的正确方法:
executable/
|- main.go (package main)
|- a.go (package main)
|- b.go (package main)
将应用程序拆分为 main、a 和 b。
关于go - 如何导入我自己在 Go 的主包中定义的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34967358/