对不起基本问题.我是GoLang的新手.
我有一个名为的自定义类型ProtectedCustomType,我不希望其中的变量set直接由调用者,而是希望Getter/ Setter方法这样做
以下是我的 ProtectedCustomType
package custom
type ProtectedCustomType struct {
name string
age int
phoneNumber int
}
func SetAge (pct *ProtectedCustomType, age int) {
pct.age=age
}
Run Code Online (Sandbox Code Playgroud)
这是我的main功能
import (
"fmt"
"./custom"
)
var print =fmt.Println
func structCheck2() {
pct := ProtectedCustomType{}
custom.SetAge(pct,23)
print (pct.Name)
}
func main() {
//structCheck()
structCheck2()
}
Run Code Online (Sandbox Code Playgroud)
但我无法继续......你能帮我解决一下如何在GoLang中实现getter-setter概念吗?
如果你想拥有setter,你应该使用方法声明:
func(pct *ProtectedCustomType) SetAge (age int) {
pct.age = age
}
Run Code Online (Sandbox Code Playgroud)
然后你就可以使用:
pct.SetAge(23)
Run Code Online (Sandbox Code Playgroud)
这种声明使您可以使用在您的结构上执行函数
(pct *ProtectedCustomType)
您正在将指针传递给您的结构,因此对它的操作会更改其内部表示.