实现search()方法以处理可选的区分大小写

时间:2018-07-13 20:58:20

标签: memory-management rust object-lifetime

Rust编程语言中,有一个chapter which implements a minigrep。我不想实现第二个search_case_insensitive()方法,而是想实现一个可以重复代码的单一API。这种尝试是这样的:

pub fn search<'a>(query: &str, lines: &'a str, case_insensitive: bool) -> Vec<&'a str> {
    let mut results = Vec::new();

    let mut query_to_search = query.clone();
    if case_insensitive {
        query_to_search = &query_to_search.to_lowercase();
    }   

    for line in lines.lines() {
        let mut line_to_search = line.clone();
        if case_insensitive {
            line_to_search = &line_to_search.to_lowercase();
        }   
        if line_to_search.contains(&query_to_search) {
            results.push(line);
        }   
    }   

    return results;
}

这会导致编译器错误:

error[E0597]: borrowed value does not live long enough
--> src/lib.rs:49:28
  |
49|         query_to_search = &query_to_search.to_lowercase();
  |                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- temporary value dropped here while still borrowed
  |                            |
  |                            temporary value does not live long enough
...
63| }
  | - temporary value needs to live until here
  |
  = note: consider using a `let` binding to increase its lifetime

此行也有类似的错误:

line_to_search = &line_to_search.to_lowercase();

我知道to_lowercase()正在创建一个新的String对象,该对象在if条件之后超出范围,这导致借位检查器引发错误。

如何延长String方法返回的to_lowercase()对象的生存期,以便在不创建重复对象以保存查询/行对象的小写版本的情况下释放该对象? >

示例:

pub fn search<'a>(query: &str, lines: &'a str, case_insensitive: bool) -> Vec<&'a str> {
    let mut results = Vec::new();

    let query_lower_case = query.to_lowercase(); // We are retaining this lower case object unnecessarily for case sensitive search
    let mut query_to_search: &str = &query.clone();
    if case_insensitive {
        query_to_search = &query_lower_case;
    }   

    for line in lines.lines() {
        let line_lower_case = line.to_lowercase(); // We are retaining this lower case object unnecessarily for case sensitive search
        let mut line_to_search: &str = &line.clone();
        if case_insensitive {
            line_to_search = &line_lower_case;
        }   
        if line_to_search.contains(&query_to_search) {
            results.push(line);
        }   
    }   

    return results;
}

0 个答案:

没有答案