GoLang中的二传手

时间:2018-10-22 14:01:58

标签: go

很抱歉出现基本问题。我是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
} 

这是我的main函数

import (
    "fmt"
    "./custom"
)
var print =fmt.Println

func structCheck2() {
    pct := ProtectedCustomType{}
    custom.SetAge(pct,23)

    print (pct.Name)
}

func main() {
    //structCheck()
    structCheck2()
}

但是我不能再继续了..您能帮我实现GoLang中的吸气剂概念吗?

1 个答案:

答案 0 :(得分:8)

如果要使用setter,则应使用方法声明:

func(pct *ProtectedCustomType) SetAge (age int)  {
    pct.age = age
}

然后您将可以使用:

pct.SetAge(23)

这种声明使您可以在结构上执行功能, 通过使用

(pct *ProtectedCustomType)

您正在传递指向您的结构的指针,因此对它的操作会更改其内部 表示形式。

您可以在this link下阅读有关此类功能的更多信息,或者 在official documentation下。