Go language package structure

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

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})
}

所以,问题是:

  1. 我读到需要在每个包文件夹中有一个package.go文件,这是正确的吗?

  2. 如果是这样,在numbers.go中,我将如何导入rational.goreal.gocomplex.go

  3. 然后,是否可以像这样编写代码:

     // 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:

  1. I read that I need to have a file package.go inside each package folder, is that right ?

  2. If so, inside numbers.go, how will I import rational.go, real.go and complex.go ?

  3. 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"

对于你的问题:

  1. 不需要。如果你在一个文件夹中有Go文件,它们会被组合成一个包,但你不必强制将一个包放入所有文件夹中。

  2. 所有的文件 rational.gocomplex.goreal.go 通常都应该以 package numbers 开头。它们都是 numbers 包的一部分,你不需要导入文件,而是导入包。当前包不需要被导入。所以:不需要。

  3. 是的。

英文:

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:

  1. 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.

  2. All the files rational.go, complex.go and real.go would normally start with package 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.

  3. Yes

huangapple
  • 本文由 发表于 2014年2月7日 07:25:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/21616276.html
匿名

发表评论

匿名网友

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

确定