英文:
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<&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?
答案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: &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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论