string - 如果字符串文字在整个程序期间都处于事件状态,那么它们如何具有不同的生命周期?

标签 string rust

我收到一个错误,“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/

相关文章:

python - 将字符串和数字读入数组

C++ 重载 >> 运算符

c++ - 如何在 C++ 中解析包含空格的字符串?

rust - vector 的借用引用的生命周期与其包含的借用指针之间有什么关系?

rust - 受管状态的静态生存期要求

php - 字符串和数组的操作

java - 当字符串中有重复项时,查找子字符串的中间索引

rust - Rust 有没有办法在不生成代码的情况下执行语法和语义分析?

rust - rust目前有类似JavaScript的setTimeout和setInterval的库实现功能吗?

class - 来自 Python 的类接口(interface)设计可以在 Rust 中得到反射(reflect)吗?