我有一个名为ProtectedCustomType
的自定义类型,我不希望调用者直接将其中的变量设为set
或get
,而是希望使用Getter / Setter
做到这一点的方法。
下面是我的ProtectedCustomType
package custom
import "fmt"
type ProtectedCustomType struct {
name string
age string
phoneNumber int
}
func (pct *ProtectedCustomType) SetAge (age string) {
pct.age=age
fmt.Println(pct.age)
}
func (pct *ProtectedCustomType) GetAge () string {
return pct.age
}
这是我的主要功能
package main
import (
"fmt"
"./custom"
)
var print =fmt.Println
func structCheck2() {
pct := custom.ProtectedCustomType{}
pct.SetAge("23")
age:=pct.GetAge
print (age)
}
func main() {
structCheck2()
}
我希望它打印23
,但它打印为0x48b950
答案 0 :(得分:3)
此(您的代码)采用pct
实例的GetAge
方法并将其存储在变量中:
age:=pct.GetAge
这将调用GetAge
方法并将其返回值存储在变量中:
age:=pct.GetAge()
考虑采用Tour of Go并阅读Go Specification以获得对Go语法的基本了解。