一个目录中可以有多个Go源文件吗?

huangapple go评论167阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2016年8月4日 13:34:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/38759175.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定