英文:
Can you have more than one Go source file in a single directory?
问题
我找到了这个问题的重复内容:链接。
你好,世界
我刚开始学习Go语言,试图弄清楚如何组织一个较大的程序。不确定是否应该使用包来分割代码,或者是否有其他更适合在单个目录中拥有多个源文件的方法,但是这是我尝试的内容。
package main
import "fmt"
func main() {
fmt.Printf("hello, world\n")
}
测试运行:
~/b2/go/src/github.com/bemmu/hello bemmu$ go run hello.go
hello, world
两个文件的版本
我想尝试将代码分割成两个文件。
main.go
package main
import "fmt"
import "say"
func main() {
say.Hello()
}
say.go
package say
import "fmt"
func Hello() {
fmt.Printf("hello, Go\n")
}
测试运行:
~/b2/go/src/github.com/bemmu/hello_split bemmu$ go run main.go
main.go:4:8: cannot find package "say" in any of:
/usr/local/go/src/say (from $GOROOT)
/Users/bemmu/b2/go/src/say (from $GOPATH)
在文档中有一个创建库并导入的示例,但在该示例中,库被放在了一个单独的目录中。
英文:
I found this to be a duplicate of this question.
Hello World
Just started learning golang and tried to figure out how to structure a larger program. Not sure if packages are the split I want or if there is something else more suitable for having multiple source files in a single directory, but here's what I tried.
package main
import "fmt"
func main() {
fmt.Printf("hello, world\n")
}
Testing running it:
~/b2/go/src/github.com/bemmu/hello bemmu$ go run hello.go
hello, world
Two file version
I wanted to try splitting it into two files.
main.go
package main
import "fmt"
import "say"
func main() {
say.Hello()
}
say.go
package say
import "fmt"
func Hello() {
fmt.Printf("hello, Go\n")
}
Testing running it:
~/b2/go/src/github.com/bemmu/hello_split bemmu$ go run main.go
main.go:4:8: cannot find package "say" in any of:
/usr/local/go/src/say (from $GOROOT)
/Users/bemmu/b2/go/src/say (from $GOPATH)
In the docs there is an example of creating a library and importing it, but in the example case it is put into a separate directory.
答案1
得分: 1
不,只需为另一个软件包创建一个新目录。
英文:
No, Just create a new directory for another package.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论