How rust store Strings in arrays?

As i know from c/c++ and general knowledge of data structures, arrays are structured as sequential memory blocks with constant size. So if I create an array of five i32 variables then array size bill be 5×4 bytes, But when I create array of strings how does it’s handled. Does it creates array of pointers and stores only memory address of string objects?

I asked question on rust but anyone knows a method how any language handles this situation can answer, probably it will be same method for every language.

>Solution :

The problem is that, as you point out, elements in an array must have a size known at compile time (called the Sized auto-trait in Rust). String is indeed Sized because it does not store its content in the String stack object, but instead in memory allocated on the heap. So yes, simplified you could say that a String array is an array of pointers.

You can see this here:

fn main() {
    let s1 = String::from("A.");
    let s2 = String::from("This is a very long string!");

    println!("String object size:");
    println!("s1: {} bytes", std::mem::size_of_val(&s1));
    println!("s2: {} bytes", std::mem::size_of_val(&s2));
    println!("");

    println!("Actual size of the contained data:");
    println!("s1: {} bytes", s1.as_str().len());
    println!("s2: {} bytes", s2.as_str().len());
    println!("");

    println!("In an array:");
    let arr = [s1, s2];
    println!("arr: {} bytes", std::mem::size_of_val(&arr));
}
String object size:
s1: 24 bytes
s2: 24 bytes

Actual size of the contained data:
s1: 2 bytes
s2: 27 bytes

In an array:
arr: 48 bytes

Leave a Reply