Borrowed value does not live long enough for assignment

someone please help im trying to convert a String to str but then when i do this it says the borrowed value 's' does not live long enough

fn placeSuits(hand: [u32; 5], mut newHand: [&'static str; 5]) -> [&'static str; 5] {
    for i in 0..4 {
        let s: String = hand[i].to_string();
        let ss: &str = &s;
        let ss = &s[..];
        newHand[i] = ss;
    }
    newHand
}

This is because you are trying to return a reference to something on the stack. This reference will get invalidated on return. Moreso, you are creating a reference to something that will be destroyed at the end of each loop.

fn placeSuits(hand: [u32; 5], mut newHand: [&'static str; 5]) -> [&'static str; 5] {
    for i in 0..4 {
        let s: String = hand[i].to_string(); // create a new owned string
        let ss: &str = &s; // reference that owned string
        let ss = &s[..];  // still a reference to the owned string s
        newHand[i] = ss; // tries to unify the lifetime 'static with the lifetime of s

        // s is dropped (destroyed) here, so it can't be unified with 'static
    }
    newHand
}

Instead of calling str::to_string, you can just copy the reference to the string and utilize that.

fn placeSuits(hand: [u32; 5], mut newHand: [&'static str; 5]) -> [&'static str; 5] {
    for i in 0..4 {
        newHand[i] = &hand[i];
    }
    newHand
}

This is fine because you are just creating a reference to the referent of another reference. This is basically just copying the reference. So the lifetimes will also be copied over, and everything will work out.


if you want to read more about the differences between str and String

Hi i tried what you did and i get new error that says expected str found u32. I am trying to convert u32 to str instead of String so when it returns its returned as an array of &str.

I really should look at the code more carefully before I post. In this case you want to use String instead of &'static str. Note that references are meant to be temporary, if you want something long lived, you need to use a String

fn placeSuits(hand: [u32; 5], mut newHand: [String; 5]) -> [String; 5] {
    for i in 0..5 { // this should probably be 5 not 4
        let s: String = hand[i].to_string();
        newHand[i] = s;
    }
    newHand
}

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