pointers - 调用结构函数给出 "cannot refer to unexported field or method"

标签 pointers struct go

我有这样的结构:

type MyStruct struct {
    Id    string
}

和函数:

func (m *MyStruct) id() {
   // doing something with id here
}

我还有一个这样的结构:

type MyStruct2 struct {
    m *MyStruct
}

现在我有一个函数:

func foo(str *MyStruct2) {
    str.m.id()
}

但是我在编译时遇到错误:

str.m.id undefined (cannot refer to unexported field or method mypackage.(*MyStruct)."".id

如何正确调用这个函数?

最佳答案

来自 http://golang.org/ref/spec#Exported_identifiers :

An identifier may be exported to permit access to it from another package. An identifier is exported if both:

  1. the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and
  2. the identifier is declared in the package block or it is a field name or method name.

所以基本上只有以大写字母开头的函数/变量才能在包外使用。

例子:

type MyStruct struct {
    id    string
}

func (m *MyStruct) Id() {
   // doing something with id here
}

//then

func foo(str *MyStruct2) {
    str.m.Id()
}

关于pointers - 调用结构函数给出 "cannot refer to unexported field or method",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57866159/

相关文章:

C++ 用派生自数组类型的对象填充数组

c++ - 将任何泛型函数作为 C++ 参数传递

c - 带有结构的for循环导致崩溃

swift - 可以通过结构扩展 Swift 字典吗?

go - 如何处理这些路由 :/example/log and/example/:id/log?

http - 如何与http.Client建立长连接?

c++ - .net c++/cli 获取指针的内容

C指针-Segment错误的解决办法是什么

c++ - 如何删除包含指向结构的指针的列表的对象?

在单值上下文中使用多值