抱歉这个基本问题。我是 GoLang 的新手。我有一个名为的自定义类型ProtectedCustomType,我不希望其中的变量set直接由调用者使用,而是希望一个Getter/Setter方法来执行此操作下面是我的ProtectedCustomTypepackage customtype ProtectedCustomType struct { name string age int phoneNumber int}func SetAge (pct *ProtectedCustomType, age int) { pct.age=age} 这是我的main功能import ( "fmt" "./custom")var print =fmt.Printlnfunc structCheck2() { pct := ProtectedCustomType{} custom.SetAge(pct,23) print (pct.Name)}func main() { //structCheck() structCheck2()}但是我无法继续进行.. 你能帮我看看如何在 GoLang 中实现 getter-setter 概念吗?
1 回答
慕斯王
TA贡献1864条经验 获得超2个赞
如果你想有 setter 你应该使用方法声明:
func(pct *ProtectedCustomType) SetAge (age int) { pct.age = age }
然后你就可以使用:
pct.SetAge(23)
这种声明使您能够通过使用
(pct *ProtectedCustomType)
您正在将指针传递给您的结构,因此对它的操作会改变其内部表示。
- 1 回答
- 0 关注
- 90 浏览
添加回答
举报
0/150
提交
取消