堆叠函数调用时了解借用变量的生命周期

时间:2018-07-24 23:18:55

标签: rust

对于我的特定情况,我似乎找不到任何关于一生的信息。 search函数具有正确的生存期并且可以正常工作,但是search_case_insensitive函数告诉我生存期太短,但是我不明白为什么。

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<(&'a str, i32)> {
    //do something
}

pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<(&'a str, i32)> {
    return search(&query.to_lowercase(), &contents.to_lowercase());
}

我得到:

error[E0597]: borrowed value does not live long enough
  --> src/lib.rs:44:43
   |
44 |     return search(&query.to_lowercase(), &contents.to_lowercase());
   |                                           ^^^^^^^^^^^^^^^^^^^^^^^ - temporary value only lives until here
   |                                           |
   |                                           temporary value does not live long enough
   |
note: borrowed value must be valid for the lifetime 'a as defined on the function body at 43:1...
  --> src/lib.rs:43:1
   |
43 | pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<(&'a str, i32)> {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   = note: consider using a `let` binding to increase its lifetime

我尝试做类似let c = contents之类的事情,并改用这个新的c值,但是遇到同样的问题。

0 个答案:

没有答案