Is it common to have struct members be pointers?

huangapple go评论71阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年10月27日 14:16:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/33361070.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定