gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:41:35 29 4
gpt4 key购买 nike

我有这样的结构:

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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com