How to sequentially create an array of &'static str in Rust with a loop?

I want to create an array called minutes: [&'static str; 60] that contains the "stringified" values from 1 to 59. So far I got:

pub const fn minutes_as_str() -> [&'static str; 60] {
    (1 ..= 59).map(|c| c.to_string()).collect()
}

However the collect() won't work with such iterator. I tried using a for loop too but the BC gets in the way:

pub const fn minutes_as_str() -> [&'static str; 60] {
    let mut result = [""; 60];
    for n in 1 ..= 59 {
        result[n] = &n.to_string(); // BC failure
    }
    result
}

Yeah, the problem is that you're creating an owned String, and then taking a reference to it on the stack. Once the closure returns, everything that doesn't get passed-on gets dropped. This means that your String will be dropped, implying that the borrow to your string becomes dangling (i.e., the reference points to junk). The rust borrow checker makes sure that unsafe things like that don't happen. You will have to instead use lazy_static and then place Strings into an array that is under a lazy_static block.

    for n in 1 ..= 59 {
        result[n] = &n.to_string(); // BC failure because n.to_string() gets dropped at the end of each loop, yet, you're trying to insert a reference to it . Thus once the for loop makes another iteration, the string gets dropped, implying the reference is now dangling. The BC will not permit that
    }

Just create a Vec<String> if you are going to figure this stuff out at run-time. Note that arrays of length 60 are not yet well supported due to restrictions in the compiler.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.