In Rust:
println!("{}", mem::size_of_val(&String::from("1234567890")));
Prints 24
.
I understand String
may store additional data, eg, the length of the string, But where do the 24 bytes come from?
use std::mem;
fn main() {
println!("{}", mem::size_of_val(&String::from("1234567890")));
return ()
}
My architecture is arm64 if it's relevant.
A String
in Rust has a size of 24 bytes, because it is composed of a pointer (8 bytes on 64bit systems) to the heap, a 8 byte length, and a 8 byte capacity.
A String
doesn’t store the data inline, as it stores the bytes of the value on the heap. If you want the length of the underlying bytes, use String::len
.
The documentation regarding a String
s representation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With