[英]Empty struct to use with reflect.TypeOf
Whats the difference between &Duck{}
and (*Duck)(nil)
? &Duck{}
和(*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
&Duck{}
points to a "Zero" struct instance, but it is most certainly not nil! &Duck{}
指向一个“零”结构实例,但它肯定不是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.
您不能对nil指针进行所有操作,无论它们具有相同的类型。
If you're just interested in checking types, I suppose a nil pointer is more efficient as there are no allocations of objects involved. 如果您只是对检查类型感兴趣,我想nil指针会更有效,因为不涉及对象分配。
So it comes down to what exactly it is you want to do. 因此,这取决于您要做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.