GoLang中的二传手 [英] Setter in GoLang
问题描述
很抱歉出现基本问题.我是GoLang的新手.
Sorry for the basic question. I am new to GoLang.
我有一个名为 ProtectedCustomType
的自定义类型,我不希望其中的变量直接由调用方进行 set
设置,而是希望使用 Getter
/ Setter
方法来实现
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
下面是我的 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中的吸气剂概念吗?
But i couldn't proceed further .. can you please help me on how to achieve getter-setter concept in GoLang ?
推荐答案
如果要使用setter,则应使用方法声明:
If you want to have setter you should use method declaration:
func(pct *ProtectedCustomType) SetAge (age int) {
pct.age = age
}
然后您将可以使用:
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.
这篇关于GoLang中的二传手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!