如果字符串文本在整个程序期间都处于活动状态,它们如何具有不同的生存期?



我收到一个错误,即"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 的整个正文来查看这一点 — 没关系。如果您花时间创建一个最小、完整和可验证的示例,您就会自己发现这一点。

由于寿命计算,该功能有效地定义为:

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>>)

最新更新