如何修复丢失的生命周期说明符?

bos*_*evs 4 lifetime rust

我有一个非常简单的方法.第一个参数采用向量组件("A",5,0),我将它与另一个向量的每个元素进行比较,看它们是否具有相同的(_,5,_),然后打印出找到的元素的字符串.

比较("A",5,0)和("Q",5,2)应打印出Q.

fn is_same_space(x: &str, y1: i32, p: i32, vector: &Vec<(&str, i32, i32)>) -> (&str) {
    let mut foundString = "";

    for i in 0..vector.len() {

        if y1 == vector[i].1 {
            foundString = vector[i].0;
        }

    }
    foundString    
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到此错误

error[E0106]: missing lifetime specifier
 --> src/main.rs:1:80
  |
1 | fn is_same_space(x: &str, y1: i32, p: i32, vector: &Vec<(&str, i32, i32)>) -> (&str) {
  |                                                                                ^ expected lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or one of `vector`'s 2 elided lifetimes
Run Code Online (Sandbox Code Playgroud)

She*_*ter 6

通过指定生命周期:

fn is_same_space<'a>(x: &'a str, y1: i32, p: i32, vector: &'a Vec<(&'a str, i32, i32)>) -> (&'a str)
Run Code Online (Sandbox Code Playgroud)

这只是对函数执行操作的许多可能解释中的一种,因此它是一种非常保守的选择 - 它使用所有引用参数的统一生命周期.

也许你想返回居住,只要一个字符串x或者只要vector或只要里面的字符串vector; 所有这些都可能有效.


强烈建议您返回并重新阅读The Rust Programming Language.它是免费的,针对Rust的初学者,它涵盖了使Rust独特的所有东西,对程序员来说是新手.许多人花了很多时间在这本书上,它回答了许多初学者的问题,比如这个问题.

具体来说,您应该阅读以下章节:

甚至还有第二版的作品,章节如下:


为了好玩,我会使用迭代器重写你的代码:

fn is_same_space<'a>(y1: i32, vector: &[(&'a str, i32, i32)]) -> &'a str {
    vector.iter()
        .rev() // start from the end
        .filter(|item| item.1 == y1) // element that matches
        .map(|item| item.0) // first element of the tuple
        .next() // take the first (from the end)
        .unwrap_or("") // Use a default value
}
Run Code Online (Sandbox Code Playgroud)