英文:
Is it common to have struct members be pointers?
问题
以go github package为例。几乎每个定义的结构体成员都是指向值的指针,而不是值本身。
这是典型的Go语言风格吗?为什么?
我理解这样做可以减小结构体的大小(假设指针的大小小于指向的值的大小),这在频繁传递结构体的情况下可能很重要。但为什么不使用值的结构体,并通过指针传递结构体呢?
英文:
Take, for example, the go github package. Just about every member of every struct defined is a pointer to a value rather than a value.
Is this idiomatic Go? Why?
I understand that it reduces the size of the struct (assuming the size of the pointer is less than the size of the value it points to) which may important if you are passing around structs by value a lot. But why not have a struct of values and pass the struct by pointer instead?
答案1
得分: 19
在github包中,原因是大多数结构体都是用于从github api的json中进行序列化/反序列化的。
他们使用*int
而不是int
的原因是因为指针的零值是nil
,而int
的零值是0
。这允许客户端区分“此字段未包含在响应中”和“此字段的值为零”。
这对于时间等事物特别有用,如果没有可空类型,你将得到很多00-00-0000类型的日期。
英文:
In the github package the reason is that most structs are intended to be serialized/deserialized from json from the github api.
The reason they use *int
instead of int
is because the zero value of a pointer is nil
, while the zero value of int
is 0
. It allows the client to distingish between "this field was not included in the response" and "the value of this field is zero".
This is particularly useful for things like times, where if you do not have nilable types, you will end up with a lot of 00-00-0000 type dates.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论