我正在阅读这本书,但我不明白为什么这个函数不能编译:
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)