【问题标题】:Go, how to import struct and fields of other packages?Go,如何导入其他包的结构和字段?
【发布时间】:2021-12-03 09:26:46
【问题描述】:

我有下一个问题,如果我尝试导出其他包的结构,调用获取日期的方法,并使用 (struct.field) 获取字段,它不起作用

//main/other
package other

type Birthday struct{
     Day string
}

func (b *Birthday) SetDay(){
     b.Day = "10"
}

//main
package main

import ("main/other")

func main(){
    f := other.Birthday{}
    f.SetDay()
    fmt.Println(f.Day) // ""   no return nothing
}

但是当我在结构的同一个文件中使用 func main 时,这个可以工作。

【问题讨论】:

  • 你能出示你的go.mod文件吗?
  • 你的实际代码能编译吗?有没有错误?在您的实际代码中,您使用的是 func (b *Birthday) SetDay() 还是可能是 func (b Birthday) SetDay()
  • 阅读并关注 (!!) golang.org/doc/#getting-started。没有捷径,没有但我知道更好,没有但我想要,没有但随机的 YT 教程说,没有但我不需要。只需要逐字逐句。

标签: go struct package


【解决方案1】:

我刚刚测试了你的程序on playground:

package main

import (
    "fmt"
    "play.ground/foo"
)

func main() {
    f := foo.Birthday{}
    f.SetDay()
    fmt.Println(f.Day)
}
-- go.mod --
module play.ground
-- foo/foo.go --
package foo

type Birthday struct {
    Day string
}

func (b *Birthday) SetDay() {
    b.Day = "10"
}

它确实工作得很好。 确保先go mod init yourProject;详见“Tutorial: Create a Go module”。

【讨论】:

    猜你喜欢
    • 2014-02-07
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 2013-08-17
    • 2022-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多