In Rust, why does `size_of::<str>()` fail to compile while `size_of::<&str>()` is 16 and `size_of::<()>()` is 0 on a 64-bit target?
answer
- the implicit Sized bound
- length travels with the pointer
- size_of_val for the run-time size
- zero bytes, alignment still counts
basics
~20 sstr is dynamically sized, and size_of::<T>() requires T: Sized, so rustc reports E0277. A &str is a wide pointer, data address plus length, 16 bytes today. () is a zero-sized type, guaranteed size 0, alignment 1.
solid answer
~40 s`std::mem::size_of::<T>()` has an implicit `T: Sized` bound, and `str`, `[T]` and `dyn Trait` are **dynamically sized types** whose size is known only per value, so `size_of::<str>()` fails with E0277: "the size for values of type `str` cannot be known at compilation time". A pointer to a DST carries the missing information beside the address: the length for `&str` and `&[T]`, a vtable pointer for `&dyn Trait`. That makes them 16 bytes on rustc 1.99.1 for a 64-bit target, though the Reference promises only that they are at least as big as a thin pointer. For the run-time size, call `size_of_val(s)`. At the other end, `()`, unit structs and `PhantomData` are **zero-sized types**: `()` is guaranteed size 0 and alignment 1, they cost nothing in a struct, and `Vec<()>` never allocates and reports `usize::MAX` capacity.
code
rust · 29 linesuse std::marker::PhantomData;
struct Marker;
struct Tagged {
id: u32,
_tag: PhantomData<Marker>,
}
trait Shape {}
impl Shape for u8 {}
fn main() {
println!("() {}", size_of::<()>());
println!("Marker {}", size_of::<Marker>());
println!("[u64; 0] {} align {}", size_of::<[u64; 0]>(), align_of::<[u64; 0]>());
println!("Tagged {}", size_of::<Tagged>());
println!("&u8 {}", size_of::<&u8>());
println!("&[u8] {}", size_of::<&[u8]>());
println!("&str {}", size_of::<&str>());
println!("&dyn Shape {}", size_of::<&dyn Shape>());
println!("Box<[u8]> {}", size_of::<Box<[u8]>>());
let s: &str = "héllo";
println!("size_of_val(s) {}", size_of_val(s));
let mut v: Vec<()> = Vec::new();
for _ in 0..1000 { v.push(()); }
println!("Vec<()> len {} cap {}", v.len(), v.capacity());
let t = Tagged { id: 1, _tag: PhantomData };
let _ = t.id;
}go deeper
Recall that str and [T] have no compile-time size, that &str carries a length, and that () takes no space.
Explain the implicit Sized bound behind E0277, use size_of_val for a run-time size, and list what wide-pointer metadata holds for slices and trait objects.
Separate guarantee from current behaviour: DST pointers are only promised to be at least thin-pointer size, and ZSTs can carry alignment greater than 1, which matters in allocators and containers.
Use zero-sized markers and HashMap<K, ()> style designs freely, and keep code from hard-coding wide-pointer sizes it was never promised.
## Two ends of the size scale Most Rust types have a size fixed at compile time: `u64` is 8, a struct is its fields plus padding. Two families break the usual picture: - **Dynamically sized types (DSTs)** have no compile-time size: `str`, slices `[T]` and trait objects `dyn Trait`. A struct whose last field is a DST is a DST too. - **Zero-sized types (ZSTs)** have size 0: `()`, unit structs like `struct Marker;`, structs whose fields are all ZSTs, `PhantomData<T>`, and empty arrays such as `[u64; 0]`. ## Why `size_of::<str>()` is rejected The signature is `pub const fn size_of<T>() -> usize`, and every generic parameter carries an implicit `T: Sized` bound unless it is written `?Sized`. `str` does not implement `Sized`, so rustc 1.99.1 reports: ```plaintext error[E0277]: the size for values of type `str` cannot be known at compilation time note: required by an implicit `Sized` bound in `std::mem::size_of` ``` The question "how big is a `str`?" only has an answer for a particular value. That is what `std::mem::size_of_val(&T) -> usize` answers, and its parameter is `?Sized`: `size_of_val("héllo")` is 6, because `é` takes two bytes in UTF-8. `align_of_val` is its counterpart for alignment. ## Wide pointers to DSTs Because a DST's size lives with the value, every pointer to one carries **metadata** next to the address: | Pointer | Metadata | Size on rustc 1.99.1, 64-bit | |---|---|---| | `&u8`, `Box<u8>` | none | 8 | | `&[u8]`, `&str`, `Box<[u8]>` | element count | 16 | | `&dyn Trait`, `Box<dyn Trait>` | vtable pointer | 16 | The Reference guarantees less than the table suggests: - a pointer to an unsized type is itself `Sized`; - its size and alignment are **at least** those of a pointer to a sized type; - `&str` has the same layout as `&[u8]`. It adds that all DST pointers are *currently* twice the size of `usize`, and says not to rely on it. The same rule reaches user types. `struct Frame { len: u16, data: [u8] }` has a slice as its last field, so `Frame` is itself a DST: it cannot live in a local by value, `size_of::<Frame>()` is rejected like `size_of::<str>()`, and a `&Frame` carries the slice length as its metadata. The nomicon calls custom DSTs "largely half-baked", because building one in practice means either a generic struct coerced from a sized version or unsafe pointer casts. So code that hard-codes 16, or splits a `&[T]` into two `usize` values by transmute, depends on a detail; `as_ptr()` and `len()` are the supported way to take a slice apart. What a trait-object pointer's vtable holds and costs is covered in the lesson on trait objects. ## Zero-sized types The Reference guarantees that `()` has **size 0 and alignment 1**, and that a struct with no fields or only zero-sized fields is zero-sized. Consequences: 1. **Free markers.** `struct Tagged { id: u32, _tag: PhantomData<Marker> }` is 4 bytes, the same as a bare `u32`. 2. **Free collections.** `HashMap<K, ()>` stores no values; this is essentially how `HashSet<K>` is built. 3. **No allocation.** The `Vec` docs say a `Vec<T>` of a zero-sized `T` never allocates and its capacity is always `usize::MAX`; pushing 1000 `()` values keeps it allocation-free. 4. **Shared addresses.** The Reference warns that a zero-sized field may have the same address as another field of the same struct, so field addresses cannot serve as identities. **Size zero does not mean alignment one.** `[u64; 0]` has size 0 and alignment 8 on rustc 1.99.1, and placing it in a struct raises that struct's alignment. This is why `#[repr(transparent)]` accepts extra fields only when they have size 0 *and* alignment 1. ## Where this shows up in unsafe code - **Writing an allocator or a container.** Allocators generally require a non-zero size, so containers special-case ZSTs instead of asking for zero bytes; `Vec` uses a dangling, aligned, non-null pointer. - **Computing buffer lengths.** `size_of::<T>() * n` is 0 for any ZST, so a byte count cannot be used to recover an element count. - **Generic code over `?Sized` types.** A function that takes `&T` with `T: ?Sized` must use `size_of_val`, because `size_of::<T>()` is not callable there.
- In Rust, what does `size_of_val` return for a `&dyn Display` pointing at a `u64`?8, the size of the `u64` behind the pointer. `size_of_val` reads the run-time size from the pointer's metadata, here the vtable, rather than measuring the pointer. The pointer itself is a separate value, 16 bytes on current 64-bit rustc.
- Why is a struct containing `[u64; 0]` and a `u8` 8 bytes rather than 1?The empty array has size 0 but alignment 8, and a struct's alignment is at least that of its most aligned field. Its size must be a multiple of that alignment, so 1 byte of data rounds up to 8.
- size_of::<str>() returns the length of the string
- A &str is a plain pointer, the same size as &u8
- The Reference guarantees DST pointers are exactly two words
- A zero-sized type always has alignment 1
- Vec<()> allocates one byte per element