英文:
Use more than one file in a Go program
问题
我希望学习如何在Go包中将我的代码逻辑上分割成多个文件,并且关键是使用该分割/独立文件在同一包的另一个文件中的语法。
我创建了一个这样形式的Go项目:
-test
-bin
-pkg
-src
-main
main.go
test.go
并尝试运行go build main
和go build main.go test.go
,但总是出现错误。
test.go只包含以下代码:
package main
import "fmt"
func do(b string) {
fmt.Println(b)
}
我想要在main.go中调用do("x")
。
现在main.go中只有以下内容:
package main
func main() {
test.do("x")
}
我不知道该怎么做才能使其工作。许多答案似乎建议将test.go移动到一个名为"test"的目录中。我希望Go不要求我为我编写的每一段代码都创建一个目录,但也许我会"违背系统"。许多答案都指向一个网站,告诉我要创建上述目录结构,并使用go install
来编译我的二进制文件,但那样做并不起作用。
我只想知道如何在包中的package/x.go文件中使用package/y.go中的函数,即使它们在同一个包中。一定有办法做到这一点,否则我要么会有很多不必要的包,要么会有难以理解的庞大文件。
我知道有很多类似的问题,但在我的搜索中,我还没有找到两个在同一包中相互引用的文件的实际示例代码。
英文:
I wish to learn how to logically split my code in a Go package into multiple files, and crucially, the syntax necessary to use that split/separate file in another file of the same package.
I have created a go project in this form
-test
-bin
-pkg
-src
-main
main.go
test.go
and attempted to run go build main
and go build main.go test.go
, but I have always got an error.
test.go contains only this code
package main
import "fmt"
func do(b string) {
fmt.Println(b)
}
I want to be able to call do("x")
in main.go.
Right now all that is in main.go is
package main
func main() {
test.do("x")
}
I do not know what to do to get this to work. Many answers seem to suggest moving test.go into a directory "test". I am hoping Go does not require me to make a directory for every piece of code I write, but maybe I would be "fighting the system". Many answers have pointed me to a website telling me to make the above directory structure, and to use go install
to compile my binaries, but that does not work.
I just want to know how to use functions in package/x.go inside package/y.go, even if they are in the same package. There has to be a way to do this, otherwise I will have either a bunch of unnecessary packages or hard to understand monolithic files.
I know there are many similar questions, but in my searching I haven't been able to find an actual example of the code in two files in the same package that reference each other.
答案1
得分: 4
test.go
必须与同一目录下的文件在同一个包中。因此,这两个文件的包名都应为main
,并且由于它们在同一个包中,你可以直接调用do("x")
。
此外,你可以使用以下方式构建整个包,而无需指定单个文件。
export GOPATH="<path to>/test"
go build main
英文:
test.go
has to be in the same package if is in the same directory. the package is thus main
for both of the files and being in the same package you can just call do("x")
.
Additionally you can build the entire package like this without specifying the single files.
export GOPATH="<path to>/test"
go build main
答案2
得分: 0
只需使用:
do
而不是:
test.do
英文:
Just use:
do
instead of:
test.do
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论