Recursive array elements

Hello Rust people!

I want realyse something about this:

    let arr2 = ["One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven "];
    let arr3  = [arr2[0], arr3[0].to_owned()+arr2[1], arr3[1].to_owned()+arr2[2],
    arr3[2].to_owned()+arr2[3], arr3[3].to_owned()+arr2[4], arr3[4].to_owned()+arr2[5],
    arr3[5].to_owned()+arr2[6]];

Or using "for" modifying construct.

How can I do this in Rust correctly using &str datatype only?

Or using something about:

let arr3[&str; 7] = {arr3[_i] = somefunc(_i)};

?

You can try this

let arr2 = ["One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven "];
let arr3: [_; 7] = std::array::from_fn(|i| {
    let mut buf = String::new();
    for s in &arr2[..i + 1] {
        buf += s;
    }
    buf
});
2 Likes

This isn’t possible in the general case, because a single &str must point to a continuous buffer and there’s no guarantee that the &strs inside arr2 are contiguous in memory. If you have a single s:&str somewhere that contains "One Two Three Four Five Six Seven ", however, you should be able to build arr3 by taking subslices [&s[..4], &s[..8], …].

3 Likes

You inspire me to do this

let arr2 = ["One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven "];
let full = arr2.join("");
let arr3: [_; 7] = {
    let mut len = 0;
    std::array::from_fn(|i| {
        len += arr2[i].len();
        &full[..len]
    })
};
2 Likes

Thank you!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.