小编Gat*_*tes的帖子

Rust - 从 `&str` 转换为 `String` 并使用闭包返回

我正在阅读这本书,但我不明白为什么这个函数不能编译:

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    contents
        .lines()                           // Fetch an iterator for each line in `contents`
        .map(|x| x.to_lowercase())         // (x is now String) Convert each line to lowercase
        .filter(|x| x.contains(query))     // Filter out lines that do not contain query
        .map(|x| x.trim())                 // Eliminate extra whitespace
        .collect()                         // Consume iterator and produce Vec<&str>
}
Run Code Online (Sandbox Code Playgroud)

如果没有该to_lowercase()行,它将运行,我猜这是因为它将返回 aString而不是&str我们最后需要输出的。但是,当我将转换替换回&strlike 时:

// -- snip --
.map(|x| x.to_lowercase().to_str())
// …
Run Code Online (Sandbox Code Playgroud)

closures ownership rust borrow-checker borrowing

1
推荐指数
1
解决办法
2004
查看次数

标签 统计

borrow-checker ×1

borrowing ×1

closures ×1

ownership ×1

rust ×1