gpt4 book ai didi

go - 做 getters 和 setters 的推荐方法

转载 作者:IT王子 更新时间:2023-10-29 02:26:08 26 4
gpt4 key购买 nike

我有一个将用 go 编写的项目,它在一个结构中有超过 30 个字段,在允许设置值之前需要验证这些字段。

在 python 中,我可能会使用描述符或至少使用属性来执行此操作,以尽可能避免样板代码。

我的问题是在 go 中执行此操作的最佳方法通常是什么?只是在结构中使用小写变量并为每个属性设置 get 和 set 函数,还是有更好的方法来防止样板代码?

最佳答案

来自go docs :

Go doesn't provide automatic support for getters and setters. There's nothing wrong with providing getters and setters yourself, and it's often appropriate to do so, but it's neither idiomatic nor necessary to put Get into the getter's name. If you have a field called owner (lower case, unexported), the getter method should be called Owner (upper case, exported), not GetOwner. The use of upper-case names for export provides the hook to discriminate the field from the method. A setter function, if needed, will likely be called SetOwner. Both names read well in practice:

owner := obj.Owner()
if owner != user {
obj.SetOwner(user)
}

关于go - 做 getters 和 setters 的推荐方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53684442/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com