0

I'm trying to insert multiple pieces into a hashmap as so

fn main() {

    let mut pieces: HashMap<&str, Piece> = HashMap::new();
    
    for column in b'a'..=b'h' {
        let column_char: char = column as char;
        let piece_position: String = format!("{}2", column_char);
        pieces.insert(piece_position.clone().as_str(), Piece { icon: "1", colour: Colour::White });
    }
}

I'm getting the following Errors:

borrowed value does not live long enough
creates a temporary value which is freed while still in use

I believe the error is due to me passing a memory location that is cleared just after the insert. I thought if I cloned piece_positions pieces would get to own the new copy and the memory of the variable would not be cleared. How would I do this as this is not working?

Taonga07
  • 36
  • 4

1 Answers1

2

Your problem is in this line piece_position.clone().as_str().

piece_position is a String that is created in loop body and then dropped at the end of it. This is de the same as the following code:

fn main() {
    let x: &str;
    {
        let y = String::from("hello");
        x = y.as_str();
    }
    println!("{x}");
}

y will be dropped at the end of nested block, so x would be a dangling pointer.

The solution is to store owned values. Change hash map to be HashMap<String, Piece>. That way an owned string will be moved into hash map.

Aleksander Krauze
  • 3,115
  • 7
  • 18
  • Changing to `String` works well, what if i want to keep using `HashMap<&str, Piece>`, is it still possible? – Xi Xiao Jun 08 '23 at 06:22