Box<str> Versus String Ownership

String spends three words on ptr, len, and capacity; Box<str> is a two-word fat pointer into one exact allocation with no growth methods.

RustData Integrity

Code

rustsnippet
18 lines
use std::mem::size_of;

fn main() {
    let owned: String = String::from("konnichiwa");

    // String owns a growable heap buffer: the ptr + len + capacity triple
    println!("size_of::<String>() = {}", size_of::<String>());
    println!("len = {}, capacity = {}", owned.len(), owned.capacity());

    // Box<str> is a fat pointer (ptr + len) into an exactly-sized allocation
    let boxed: Box<str> = owned.clone().into_boxed_str();
    println!("size_of::<Box<str>>() = {}", size_of::<Box<str>>());
    println!("boxed len = {}", boxed.len());

    // Box<str> has no push_str: growing means converting back to a String
    let grown: String = boxed.into();
    println!("grown = {grown}");
}

How it works

One way to read it: the function main, doing all the work.

Caveats

  • No dependencies section needed; the standard library is the whole story.

Using it

The main signature reads fn main()

Output lines are prefixed (size_of::<String>() =, len =, size_of::<Box<str>>() =), making each step’s effect easy to spot.

Key statements

let boxed: Box<str> = owned.clone().into_boxed_str();

Interactive Tools for This Topic

FAQ

What does Box<str> Versus String Ownership print when run?
Invoke the file as-is — the `size_of::<String>() =`, `len =`, `size_of::<Box<str>>() =` prefixes identify which step printed each line.