我得到一个错误,即“ xo”和向量向量中的字符串文字具有不同的生存期。通过Strings
将文字转换为to_string()
可以找到一种解决方法,但我仍然想了解这个错误。
fn main() {
let mut tic_tac = vec![
vec!["[ ]", "[ ]", "[ ]"],
vec!["[ ]", "[ ]", "[ ]"],
vec!["[ ]", "[ ]", "[ ]"],
];
let letter = "[x]";
make_move(&letter, 1, &mut tic_tac);
make_move(&letter, 4, &mut tic_tac);
}
fn make_move(xo: &str, position: i32, board: &mut Vec<Vec<&str>>) {
if position < 4 && position <= 1 {
match position {
1 => board[0][0] = xo,
2 => board[0][1] = xo,
3 => board[0][2] = xo,
_ => (),
}
}
}
error[E0623]: lifetime mismatch
--> src/main.rs:18:32
|
15 | fn make_move(xo: &str, position: i32, board: &mut Vec<Vec<&str>>) {
| ---- ----
| |
| these two types are declared with different lifetimes...
...
18 | 1 => board[0][0] = xo,
| ^^ ...but data from `xo` flows into `board` here
答案 0 :(得分:2)
您的函数不知道只会使用字符串文字来调用它。您可以通过删除main的整个主体来看到这一点-没关系。如果您花时间创建Minimal, Complete, and Verifiable example,那么您将自己发现它。
由于lifetime elision,该函数有效地定义为:
fn make_move<'a, 'b>(xo: &'a str, position: i32, board: &mut Vec<Vec<&'b str>>)
实际上,这两个生命周期彼此无关,您会收到错误消息。
说它们是相同的生命周期可以解决它:
fn make_move<'a>(xo: &'a str, position: i32, board: &mut Vec<Vec<&'a str>>)
正如您所说的那样,保存在面板中的值为'static
:
fn make_move(xo: &'static str, position: i32, board: &mut Vec<Vec<&str>>)