去语言包结构 [英] Go language package structure
问题描述
我在 $ GOPATH
中设置了一个项目,类似于这样的结构: p>
$ GOPATH /
github.com/
用户名/
项目名称/
main .go
数字/
rational.go
real.go
complex.go
我的主要是:
$ p $ 包主
导入(
fmt
./numbers
)
func main(){
fmt.Println(numbers.Real {2.0})
}
所以问题是:
-
我读到我需要在每个包文件夹中有一个文件
package.go
,是吗? -
如果是这样,insid e
numbers.go
,我将如何导入rational.go
,real.go
和
complex.go
? -
然后,是否有可能有东西例如:
// real.go
包裹号码
类型Real struct {
Number float64
}
...在主do fmt.Println(numbers.Real {2.0})
?
src
:它应该是`$ GOPATH / src / github.com/ ... 第二:不要使用相对导入。只是不要这样做。导入包裹号码如导入github.com/username/projectname/number
回答您的问题:
-
没有。如果您在文件夹中包含Go文件,那么这些文件会合并到一个包中,但您并不强制将包放入所有文件夹中。
所有文件 -
是
rational.go
, complex.go
和 real.go
通常会从包号码
开始。这些都是软件包号码的一部分,您不是包含文件而是包。当前包不需要导入。所以:不。
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.go
inside each package folder, is that right ?If so, inside
numbers.go
, how will I importrational.go
,real.go
andcomplex.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})
?
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.go
andreal.go
would 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
这篇关于去语言包结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!