How do I fix a missing lifetime specifier?

丶灬走出姿态 提交于 2019-12-05 17:20:42
Shepmaster

By specifying a lifetime:

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

This is only one of many possible interpretations of what you might have meant for the function to do, and as such it's a very conservative choice - it uses a unified lifetime of all the referenced parameters.

Perhaps you wanted to return a string that lives as long as x or as long as vector or as long as the strings inside vector; all of those are potentially valid.


I strongly recommend that you go back and re-read The Rust Programming Language. It's free, and aimed at beginners to Rust, and it covers all the things that make Rust unique and are new to programmers. Many people have spent a lot of time on this book and it answers many beginner questions such as this one.

Specifically, you should read the chapters on:

There's even a second edition in the works, with chapters like:


For fun, I'd rewrite your code using iterators:

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
}

So the problem comes from the fact that vector has two inferred lifetimes, one for vector itself (the &Vec part) and one for the &str inside the vector. You also have an inferred lifetime on x, but that really inconsequential.

To fix it, just specify that the returned &str lives as long as the &str in the vector:

fn is_same_space<'a>(                        // Must declare the lifetime here
    x: &str,                                 // This borrow doesn't have to be related (x isn't even used)
    y1: i32,                                 // Not borrowed
    p: i32,                                  // Not borrowed or used
    vector: &'a Vec<(&'a str, i32, i32)>     // Vector and some of its data are borrowed here
) -> &'a str {                               // This tells rustc how long the return value should live
    ...
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!