将变量传递给函数以在Rust中重新创建它

huangapple go评论66阅读模式
英文:

Passing a variable so a function recreates it in rust

问题

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 'a'..'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?

英文:

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

fn main() {

    let mut pieces: HashMap&lt;&amp;str, Piece&gt; = HashMap::new();
    
    for column in b&#39;a&#39;..=b&#39;h&#39; {
        let column_char: char = column as char;
        let piece_position: String = format!(&quot;{}2&quot;, column_char);
        pieces.insert(piece_position.clone().as_str(), Piece { icon: &quot;1&quot;, 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?

答案1

得分: 2

你的问题在这行代码中 piece_position.clone().as_str()

piece_position 是一个在循环体中创建并在循环结束时丢弃的 String。这与以下代码相同:

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

y 将在嵌套块的末尾被丢弃,因此 x 将成为一个悬空指针。

解决方案是存储拥有的值。将哈希映射更改为 HashMap<String, Piece>。这样,拥有的字符串将被移动到哈希映射中。

英文:

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: &amp;str;
    {
        let y = String::from(&quot;hello&quot;);
        x = y.as_str();
    }
    println!(&quot;{x}&quot;);
}

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&lt;String, Piece&gt;. That way an owned string will be moved into hash map.

huangapple
  • 本文由 发表于 2023年6月8日 04:12:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76426807.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定