英文:
Empty struct to use with reflect.TypeOf
问题
&Duck{} 和 (*Duck)(nil) 之间有什么区别?有没有理由更喜欢其中之一?
这两者之间的区别在于它们的类型和用途不同。
&Duck{} 是一个指向 Duck 类型的指针,它指向一个新创建的 Duck 对象。这种方式可以用于创建一个新的 Duck 对象,并获取指向该对象的指针。
(*Duck)(nil) 是一个空指针,它的类型是 *Duck。这种方式可以用于表示一个空的 Duck 指针。
在使用上的区别是:
&Duck{}创建了一个新的Duck对象,并返回指向该对象的指针。(*Duck)(nil)表示一个空的Duck指针。
在上面的示例中,reflect.TypeOf(&Duck{}) == reflect.TypeOf((*Duck)(nil)) 返回 true,说明它们的类型是相同的。
nil == (*Duck)(nil) 和 nil == &Duck{} 分别返回 true 和 false,说明它们与 nil 的比较结果是不同的。
选择使用哪种方式取决于具体的需求和上下文。如果需要创建一个新的对象并获取指向该对象的指针,可以使用 &Duck{}。如果只需要表示一个空的指针,可以使用 (*Duck)(nil)。
英文:
Whats the difference between &Duck{} and (*Duck)(nil)?
Is there any reason to prefer one over the other?
ex:
fmt.Println(reflect.TypeOf(&Duck{}) == reflect.TypeOf((*Duck)(nil)))//true
fmt.Println(nil == (*Duck)(nil))//true
fmt.Println(nil == &Duck{})//false
答案1
得分: 2
&Duck{}指向一个"Zero"结构体实例,但它肯定不是nil!你可以给它赋值。而对于nil指针,无论它们具有相同的类型,你都不能这样做。
如果你只是对检查类型感兴趣,我想nil指针更高效,因为不涉及对象的分配。
所以关键是你想要做什么。
英文:
&Duck{} points to a "Zero" struct instance, but it is most certainly not nil! You can assign values to it. You can't do all that to a nil pointer, regardless of the fact that they have the same type.
If you're just interested in checking types, I suppose a nil pointer is more efficient as there are no allocations of objects involved.
So it comes down to what exactly it is you want to do.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论