Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rust, why does size_of_val() for a 10 character string return 24 bytes?

Tags:

rust

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.

like image 300
mikemaccana Avatar asked Oct 16 '25 03:10

mikemaccana


1 Answers

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 Strings representation

like image 55
PatientPenguin Avatar answered Oct 18 '25 17:10

PatientPenguin