我收到一个错误,“xo”和向量向量中的字符串文字具有不同的生命周期。我能够通过 to_string()
将文字转换为 Strings
找到解决方法,但我仍然想了解这个错误。
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
最佳答案
您的函数不知道它只会用字符串文字调用。您可以通过删除 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>>)
关于string - 如果字符串文字在整个程序期间都处于事件状态,那么它们如何具有不同的生命周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51752650/