What is `Box<str>` and how is it different from `String` in Rust?

#110 · 🔥 214 · 💬 204 · one year ago · mahdi.blog · asimpletune · 📷
Today I and a friend went down a rabbit hole about Rust and how it manages the heap when we use Box, or String, or Vec, and while we were at it, I found out there is such a thing as Box<str>, which might look a bit strange to an untrained eye, since most of the time the str primitive type is passed around as &str. TL;DR:. Box<str> is a primitive str allocated on the heap, whereas String is actually a Vec<u8>, also allocated on the heap, which allows for efficient removals and appends. 0x000000016fdfed80: boxed str =. Okay, so a Box<str> is much simpler than a String: there is no Vec, and no capacity, and the underlying data is a primitive str that does not allow efficient appending or removing. Println!("Size of boxed str on stack:". Size of boxed str on stack: 16 size of string on stack: 24. Html $ cargo run -bin box-str-dhat Finished dev target(s) in 0.01s Running `target/debug/box-str-dhat` boxed str: hello dhat: Total: 1,029 bytes in 2 blocks dhat: At t-gmax: 1,029 bytes in 2 blocks dhat: At t-end: 1,024 bytes in 1 blocks dhat: The data has been saved to dhat-heap. The only use case for Box<str> over String that I can think of, is optimising for memory usage when the string is fixed and you do not intend to append or remove from it.
What is `Box&lt;str&gt;` and how is it different from `String` in Rust?



Send Feedback | WebAssembly Version (beta)