英文:
How to use multiple .go files in the same application
问题
大家早上好,
我是Go语言的新手。我想将一些函数移到单独的文件中,这样最后就不会有一个有1万行代码的.go文件了,哈哈。我创建了两个文件,它们都有相同的包名叫做main。我需要将包名改成特定的应用程序吗?无论如何,我该如何让这两个文件进行通信呢?
示例:
MainFile.go:
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello World!")
Test()
}
NewFile.go:
package main
import (
"fmt"
)
func Test() {
fmt.Println("Hello World Again!")
}
测试方法在第二个文件中,但第一个文件无法调用它。我确定这是我遗漏的一些基础知识。
谢谢
更新:
我尝试在命令行上指定这样的命令:go build MainFile.go NewSourceFile.go。它没有返回错误,但是没有生成二进制文件。我该如何输出二进制文件呢?
英文:
Good Morning All,
I am new to Golang. I want to move some of my functions out into separate files so that I will not have like a 10,000 line .go file at the end. lol. I created two files both have the same package called main. Do I need to change package name to be app specific? Anyway how do I get these two files to talk?
Example:
MainFile.go:
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello World!")
Test()
}
NewFile.go:
package main
import (
"fmt"
)
func Test() {
fmt.Println("Hello World Again!")
}
The test method is in the second file but cannot be reached by the first. I am sure this is some rudimentary thing I am missing.
Thanks
Update:
I tried specifying this on the command line: go build MainFile.go NewSourceFile.go. It comes back with no errors but never builds the binary. How do I get it to output the binary now?
答案1
得分: 2
如果你运行go run MainFile.go
,Test()
将找不到,因为它不在该文件中。你需要构建该包,然后运行该包:
在包含这两个文件的文件夹中运行go build
,你将在该文件夹中得到一个二进制文件。然后只需运行该二进制文件:./MyPackage
英文:
If you run go run MainFile.go
, Test()
won't be found because its not in that file. You have to build the package then run the package:
Inside the folder where the 2 files are, run go build
and you will get a binary in that folder. Then just run the binary: ./MyPackage
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论