英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论