Silly Freak
Silly Freak

Reputation: 4231

Why does size_of::<&T>() == size_of::<usize>() depend on whether T is Sized?

The docs for size_of say the following:

If T is Sized, all of those types [pointer types such as &T] have the same size as usize.

Why that qualifier? Would a pointer not have a definitive size regardless of any property of the type being pointed to?

Upvotes: 3

Views: 84

Answers (1)

Benjamin Lindley
Benjamin Lindley

Reputation: 103733

Unsized object references have extra data in addition to the pointer to the object. In the case of slice references (&[T]), they contain a size in order to indicate how long this slice is. And in the case of references to traits (trait objects), they contain a pointer to a vtable in order to enable dynamic dispatch.

Upvotes: 5

Related Questions