What does `(*RawMessage)(nil)` mean?

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

What does `(*RawMessage)(nil)` mean?

问题

Effective Go的"接口检查"部分中,建议使用以下代码进行编译时检查,以确保RawMessage实现了Marshaler接口:

var _ json.Marshaler = (*RawMessage)(nil)

我理解这个赋值语句是用来进行类型检查的,但是右边的表达式实际上表示什么意思呢?

英文:

The section Interface checks from Effective Go recommends

var _ json.Marshaler = (*RawMessage)(nil)

as a compile-time check that RawMessage implements Marshaler.

I get how the assignment does the type check but what does the right side actually mean?

答案1

得分: 7

好的,我明白了。它创建了一个新的*RawMessage(指向RawMessage的指针),通过将nil转换为*RawMessage来使其为nil。我本来期望的是:

*RawMessage(nil)

但是这样不起作用,因为转换似乎比指针操作符具有更高的优先级,所以它会变成一个解引用操作。

英文:

Ok, I figured it out. It creates a new *RawMessage (pointer to RawMessage) that is nil by casting nil to *RawMessage. I would have expected

*RawMessage(nil)

but that doesn't work because the <strike>cast</strike> conversion seems to take precedence over the pointer operator, so it would become a dereference.

huangapple
  • 本文由 发表于 2016年3月27日 15:47:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/36245061.html
匿名

发表评论

匿名网友

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

确定