douganggu4392 2018-10-22 14:01
浏览 31
已采纳

GoLang中的二传手

Sorry for the basic question. I am new to GoLang.

I have a custom type named ProtectedCustomType and I don't want the variables within that to be set directly by the caller, rather want a Getter / Setter methods to do that

Below is my ProtectedCustomType

package custom

type ProtectedCustomType struct {
    name string
    age int
    phoneNumber int
}

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

And here is my main function

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

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

    print (pct.Name)
}

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

But i couldn't proceed further .. can you please help me on how to achieve getter-setter concept in GoLang ?

  • 写回答

1条回答 默认 最新

  • dongpang2483 2018-10-22 14:04
    关注

    If you want to have setter you should use method declaration:

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

    and then you will be able to use:

    pct.SetAge(23)
    

    This kind of declarations enables you to execute function on your structure, by using

    (pct *ProtectedCustomType)

    Your are passing pointer to your struct so operations on it changes its internal representation.

    You can read more about this kind of function under this link, or under official documentation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题