GoLang中的Getter

时间:2018-10-22 17:04:46

标签: go

我有一个名为ProtectedCustomType的自定义类型,我不希望调用者直接将其中的变量设为setget,而是希望使用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

1 个答案:

答案 0 :(得分:3)

此(您的代码)采用pct实例的GetAge方法并将其存储在变量中:

age:=pct.GetAge

这将调用GetAge方法并将其返回值存储在变量中:

age:=pct.GetAge()

考虑采用Tour of Go并阅读Go Specification以获得对Go语法的基本了解。