小编典典

GoLang中的二传手

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中的吸气剂概念吗?


阅读 306

收藏
2020-07-02

共1个答案

小编典典

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

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

然后您将可以使用:

pct.SetAge(23)

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

(pct *ProtectedCustomType)

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

您可以在此链接官方文档中了解有关此功能的更多信息。

2020-07-02