抱歉问这个基本问题。我是 Go 语言的新手。
我有一个名为的自定义类型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
}
这是我的main
功能
import (
"fmt"
"./custom"
)
var print =fmt.Println
func structCheck2() {
pct := ProtectedCustomType{}
custom.SetAge(pct,23)
print (pct.Name)
}
func main() {
//structCheck()
structCheck2()
}
但我无法继续下去..你能帮我了解如何在 GoLang 中实现 getter-setter 概念吗?
如果你想有setter,你应该使用方法声明:
func(pct *ProtectedCustomType) SetAge (age int) {
pct.age = age
}
然后您将能够使用:
pct.SetAge(23)
这种声明使您能够在结构上执行函数,
通过使用
(pct *ProtectedCustomType)
您正在将指针传递给您的结构,因此对其进行的操作会更改其内部
表示。
您可以在下面阅读有关此类功能的更多信息这个链接 http://golangtutorials.blogspot.com/2011/06/methods-on-structs.html, 或者
在下面官方文档 https://golang.org/ref/spec#Method_declarations.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)