【问题标题】:Subfolder call folder Golang子文件夹调用文件夹 Golang
【发布时间】:2021-07-28 08:45:51
【问题描述】:

我的项目名称是家庭。我想使用在father.go中定义的struct,在son.go中使用。我该怎么办?

【问题讨论】:

    标签: go import subdirectory


    【解决方案1】:

    go.mod:

    module family
    

    father\father.go:

    package father
    type Dad struct { Age int }
    

    father\son\son.go:

    package main
    
    import (
       "family/father"
       "fmt"
    )
    
    func main() {
       d := father.Dad{40}
       fmt.Println(d)
    }
    

    【讨论】:

    • 嗨,如果之前在father.go里面必须导入使用son.go的数据,我该怎么做? @史蒂文便士
    • @manhkhoa168,你不能因为那将是一个导入周期。关于 SO 有很多关于此的问题,但简而言之:不要创建小包。使father.go 和son.go 成为同一个包的一部分。
    【解决方案2】:
    1. father/father.go
    package father
    type Father struct {
        Name string `json:"name"`
        Job string `json:"job"`
    }
    

    2.father/son/son.go

    package son
    
    import (
        "fmt"
        "github.com/yaocanwei/demo/father"
    )
    
    type Son struct {
        father.Father
        Hobby string `json:"hobby"`
    }
    
    func (son *Son) EchoJob() string {
        return fmt.Sprintf("%s", son.Father.Job)
    }
    

    3.main.go

    
    package main
    
    import (
        "fmt"
        "github.com/yaocanwei/demo/father/son"
    )
    
    func main()  {
        s := &son.Son{}
        s.Job = "senior engineer"
        fmt.Println(s.EchoJob())
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-18
      • 2021-06-04
      • 1970-01-01
      • 2014-06-23
      相关资源
      最近更新 更多