std::mem::size_of::<&[T]>() == 2 * std::mem::size_of::<usize>()?

    println!("{:?}", std::mem::size_of::<&[u8]>());
    println!("{:?}", std::mem::size_of::<&[u16]>());
    println!("{:?}", std::mem::size_of::<&[u32]>());

returns 16 for all 3.

From googling around, a slice appears to consist exactly of a ref & a len (usize).

Thus, is it true that sizeof(slice) always = 2 * sizeof(usize) ?

The size of &[T], yes. ([T] is dynamically sized.)

I don't think this is technically guaranteed (if e.g. Rust grows a new platform-dependent type so that ssize and pointer-sized types can be split)... but seems unlikely to change any time soon or ever for platforms where these are the same size.

1 Like

The &[T] type has a std::ptr::Pointee implementation where the metadata field is a single usize, which means a slice reference will consist of a single pointer and a usize (i.e. 16 bytes).

That trait (and therefore the implementations of it) is still unstable though, so there are no guarantees it'll always be that way. It may also be thrown out completely if a better mechanism for implementing/representing fat pointers is found.

2 Likes

In summary, basically:

  • currently, sizeof(&[T])= sizeof(ptr) + sizeof(usize)
  • currently, sizeof(ptr) = sizeof(usize)
1 Like

Sort of. Raw pointers can also be fat pointers, e.g. size_of::<*const [u8]>() is two usizes (so 16 bytes on a 64-bit target or 8 bytes on a 32-bit target). The general rule is that if P<T> is a pointer "type family", e.g. &'a T, Box<T>, *const T, or Arc<T>, then size_of::<P<T>>() == size_of::<usize>() when T: Sized (P<T> is a thin pointer) and size_of::<P<T>>() == 2 * size_of::<usize>() when T: !Sized (like a slice or trait object type; P<T> is a fat pointer). You can see a list of types that behave this way at the docs page for CoerceUnsized, under "Implementors".

As quinedot mentioned, there has been a bit of discussion on IRLO about supporting architectures where thin pointers like *const () are more than one usize big, but that is far away from turning into anything concrete afaict.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.