英文:
Go language package structure
问题
我正在尝试学习Go并遵循现有的约定,但是,像每个约定一样,在使用它们之前,你需要先理解它们,经过一些研究后,我没有找到对我以下问题的确切答案:
我在$GOPATH中设置了一个项目,遵循类似这样的结构:
$GOPATH/
github.com/
username/
projectname/
main.go
numbers/
rational.go
real.go
complex.go
我的main.go文件内容如下:
package main
import(
"fmt"
"./numbers"
)
func main() {
fmt.Println(numbers.Real{2.0})
}
所以,问题是:
-
我读到需要在每个包文件夹中有一个
package.go文件,这是正确的吗? -
如果是这样,在
numbers.go中,我将如何导入rational.go,real.go和complex.go? -
然后,是否可以像这样编写代码:
// real.go package numbers type Real struct { Number float64 }
... 然后在main函数中使用fmt.Println(numbers.Real{2.0})?
英文:
I am trying to learn Go and to follow the existing conventions, but, as every convention, you need to first understand them before use them well, and after some research, I didn't find an exact answer to my following question:
I've set up a project inside my $GOPATH, following a similar structure like this:
$GOPATH/
github.com/
username/
projectname/
main.go
numbers/
rational.go
real.go
complex.go
My main is:
package main
import(
"fmt"
"./numbers"
)
func main() {
fmt.Println(numbers.Real{2.0})
}
So, the questions are:
-
I read that I need to have a file
package.goinside each package folder, is that right ? -
If so, inside
numbers.go, how will I importrational.go,real.goandcomplex.go? -
And then, is it possible to have something like:
// real.go package numbers type Real struct { Number float64 }
... and in main do fmt.Println(numbers.Real{2.0}) ?
答案1
得分: 10
首先:你的设置缺少文件夹 src:应该是 `$GOPATH/src/github.com/..."。
其次:不要使用相对导入。不要这样做。像这样导入包 import "github.com/username/projectname/number"。
对于你的问题:
-
不需要。如果你在一个文件夹中有Go文件,它们会被组合成一个包,但你不必强制将一个包放入所有文件夹中。
-
所有的文件
rational.go、complex.go和real.go通常都应该以package numbers开头。它们都是 numbers 包的一部分,你不需要导入文件,而是导入包。当前包不需要被导入。所以:不需要。 -
是的。
英文:
First: Your Setup misses the folder src: It should be `$GOPATH/src/github.com/..."
Second: Do not use relative imports. Just do not do it. Import package numbers like import "github.com/username/projectname/number"
To your questions:
-
No. If you have Go files in a folder the are combined to a package but you are not force to put a package into all folders.
-
All the files
rational.go,complex.goandreal.gowould normally start withpackage numbers. The are all part of package numbers and you do not include files but packages. The current package need not be imported. So: No. -
Yes
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论