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

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

Passing a variable so a function recreates it in rust

问题

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

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

I'm getting the following Errors:

  1. borrowed value does not live long enough
  2. 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

  1. fn main() {
  2. let mut pieces: HashMap&lt;&amp;str, Piece&gt; = HashMap::new();
  3. for column in b&#39;a&#39;..=b&#39;h&#39; {
  4. let column_char: char = column as char;
  5. let piece_position: String = format!(&quot;{}2&quot;, column_char);
  6. pieces.insert(piece_position.clone().as_str(), Piece { icon: &quot;1&quot;, colour: Colour::White });
  7. }
  8. }

I'm getting the following Errors:

  1. borrowed value does not live long enough
  2. 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。这与以下代码相同:

  1. fn main() {
  2. let x: &str;
  3. {
  4. let y = String::from("hello");
  5. x = y.as_str();
  6. }
  7. println!("{}", x);
  8. }

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:

  1. fn main() {
  2. let x: &amp;str;
  3. {
  4. let y = String::from(&quot;hello&quot;);
  5. x = y.as_str();
  6. }
  7. println!(&quot;{x}&quot;);
  8. }

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:

确定