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

2023-11-21

我有一个非常简单的方法。第一个参数接受向量分量 ("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    
}

但是,我收到这个错误

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

By 指定生命周期:

fn is_same_space<'a>(x: &'a str, y1: i32, p: i32, vector: &'a Vec<(&'a str, i32, i32)>) -> (&'a str)

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

也许您想返回一个存在时间只要x或只要vector或者只要里面的字符串vector;所有这些都可能有效。


I 强烈推荐你回去重读Rust 编程语言。它是免费的,面向 Rust 初学者,涵盖了 Rust 独特且对程序员来说陌生的所有内容。很多人都花了a lot花在这本书上的时间和它的答案many诸如此类的初学者问题。

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

  • 所有权
  • 参考文献和借用
  • 寿命

甚至还有一个第二版正在制作中,章节如下:

  • 了解所有权
  • 通用类型、特征和生命周期

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

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
}
  • 删除了不需要的参数。
  • 使用迭代器可以避免边界检查的开销,并且更清楚地暴露您的意图。
  • 铁锈不使用camelCase变量名称。
  • 我假设您确实想从内部返回字符串vector.
  • 删除返回类型上的多余括号
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何修复丢失的生命周期说明符? 的相关文章

随机推荐