Pointers 调用struct函数会给出;无法引用未报告的字段或方法";

Pointers 调用struct函数会给出;无法引用未报告的字段或方法";,pointers,struct,go,Pointers,Struct,Go,我有一个类似这样的结构: type MyStruct struct { Id string } type MyStruct2 struct { m *MyStruct } 和功能: func (m *MyStruct) id() { // doing something with id here } func foo(str *MyStruct2) { str.m.id() } 我还有另一个类似的结构: type MyStruct struct {

我有一个类似这样的结构:

type MyStruct struct {
    Id    string
}
type MyStruct2 struct {
    m *MyStruct
}
和功能:

func (m *MyStruct) id() {
   // doing something with id here
}
func foo(str *MyStruct2) {
    str.m.id()
}
我还有另一个类似的结构:

type MyStruct struct {
    Id    string
}
type MyStruct2 struct {
    m *MyStruct
}
现在我有一个函数:

func (m *MyStruct) id() {
   // doing something with id here
}
func foo(str *MyStruct2) {
    str.m.id()
}
但我在编译时遇到了错误:

str.m.id undefined (cannot refer to unexported field or method mypackage.(*MyStruct)."".id
如何正确调用此函数?

来自:

可以导出标识符以允许从另一个标识符访问它 包裹如果出现以下两种情况,则导出标识符:

  • 标识符名称的第一个字符是Unicode大写字母(Unicode类“Lu”);及
  • 标识符在包块中声明,或者是字段名或方法名
  • 因此,基本上只有以大写字母开头的函数/变量才能在包外使用

    例如:

    type MyStruct struct {
        id    string
    }
    
    func (m *MyStruct) Id() {
       // doing something with id here
    }
    
    //then
    
    func foo(str *MyStruct2) {
        str.m.Id()
    }
    

    如果将
    MyStruct.Id
    更改为
    MyStruct.Id

    • 您将无法再访问它来初始化
      MyStruct2
    • id
      只能通过它自己的包访问:第一个
      
      
    • 因为:
      MyStruct
      MyStruct2
      在不同的包中

    要解决问题,您可以这样做:

    第一个

    package first
    
    type MyStruct struct {
        // `id` will be invisible outside of `first` package
        // because, it starts with a lowercase letter
        id string
    }
    
    // `Id()` is visible outside to `first` package 
    // because, it starts with an uppercase letter
    func (m *MyStruct) Id() string {
      return m.id
    }
    
    // Create a constructor function to return `*MyStruct`
    func NewMyStruct(id string) *MyStruct {
        return &MyStruct{
            id: id,
        }
    }
    
    第二个

    package second
    
    // Import MyStruct's package
    import "first"
    
    type MyStruct2 struct {
        // If you don't use `m` here as in your question, 
        // `first.MyStruct` will be promoted automatically.
        //
        // So, you can reach its methods directly, 
        // as if they're inside `MyStruct2`
        *first.MyStruct
    }
    
    // You can use `Id()` directly because it is promoted
    // As if, inside `MyStruct2`
    func foo(str *MyStruct2) {
        str.Id()
    }
    
    // You can initialize `MyStruct2` like this:
    func run() {
        foo(&MyStruct2{
            MyStruct: first.NewMyStruct("3"),
        })
    }
    

    这才是最要紧的事<因此,基本上只有以---大写字母---开头的函数/变量可以在
    之外使用。非常感谢。有趣的是,没有其他帖子谈论这一点。他们都提出了不同的方法来绕过这个问题。谢谢,我同意这一点。资本化很重要。金娜固执己见吗