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.
Code
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
Box Shadow GeneratorBuild CSS box-shadow values with offset, blur, spread, color, opacity, and inset controls, with a live preview of the result.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.