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 中实现 getter-setter 概念吗?


米脂
浏览 91回答 1
1回答

慕斯王

如果你想有 setter 你应该使用方法声明:func(pct *ProtectedCustomType) SetAge (age int)  {     pct.age = age }然后你就可以使用:pct.SetAge(23)这种声明使您能够通过使用(pct *ProtectedCustomType)您正在将指针传递给您的结构,因此对它的操作会改变其内部表示。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go