当前位置: > > > > Go 语言的 Setter
Go 语言的 Setter
来源:stackoverflow
2024-04-20 20:15:36
0浏览
收藏
Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《Go 语言的 Setter》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!
问题内容
很抱歉问了这个基本问题。我是 go 语言新手。
我有一个名为 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 概念吗?
解决方案
如果你想有setter,你应该使用方法声明:
func(pct *protectedcustomtype) setage (age int) {
pct.age = age
}
然后您将可以使用:
pct.SetAge(23)
这种声明使您能够在结构上执行函数, 通过使用
(pct *protectedcustomtype)
您正在将指针传递给您的结构,因此对其进行的操作会更改其内部 代表。
您可以在 下阅读有关此类功能的更多信息,或者 下 。
今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注米云公众号,一起学习编程~
