去语言包结构 [英] Go language package structure

查看:82
本文介绍了去语言包结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图学习Go并遵循现有的惯例,但是,按照每个惯例,在使用它们之前,您需要首先了解它们,并且在进行一些研究之后,我没有找到我的后续问题的确切答案:



我在 $ GOPATH 中设置了一个项目,类似于这样的结构: p>

  $ GOPATH / 
github.com/
用户名/
项目名称/
main .go
数字/
rational.go
real.go
complex.go

我的主要是:

$ p $ 包主

导入(
fmt
./numbers


func main(){
fmt.Println(numbers.Real {2.0})
}

所以问题是:


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


  2. 如果是这样,insid e numbers.go ,我将如何导入 rational.go real.go complex.go


  3. 然后,是否有可能有东西例如:

      // real.go 
    包裹号码

    类型Real struct {
    Number float64
    }


...在主do fmt.Println(numbers.Real {2.0})

解决首先:您的安装程序会忽略文件夹 src :它应该是`$ GOPATH / src / github.com/ ...



第二:不要使用相对导入。只是不要这样做。导入包裹号码如导入github.com/username/projectname/number



回答您的问题:


  1. 没有。如果您在文件夹中包含Go文件,那么这些文件会合并到一个包中,但您并不强制将包放入所有文件夹中。

  2. 所有文件 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:

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

解决方案

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

这篇关于去语言包结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆