Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading