简体   繁体   中英

Empty struct to use with reflect.TypeOf

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

&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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM