Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rust 具有多个生命周期的迭代器_Rust - Fatal编程技术网

Rust 具有多个生命周期的迭代器

Rust 具有多个生命周期的迭代器,rust,Rust,考虑以下方法: fn search Vec(查询:&str,文本:&'a str)->impl迭代器(查询:&'a str,文本:&'a str)->impl迭代器(查询:&'a str,文本:&'a str)->impl迭代器闭包通过引用捕获变量,除非变量是从闭包中使用(移动)的 在这里,闭包通过引用捕获查询,这意味着它存储了对引用的引用,因此,闭包不需要query的所有权 现在,闭包捕获了对局部变量的引用,函数试图返回该闭包的所有权 修复方法很简单:将move添加到闭包中,以便捕获query

考虑以下方法:


fn search Vec(查询:&str,文本:&'a str)->impl迭代器(查询:&'a str,文本:&'a str)->impl迭代器(查询:&'a str,文本:&'a str)->impl迭代器闭包通过引用捕获变量,除非变量是从闭包中使用(移动)的

在这里,闭包通过引用捕获
查询
,这意味着它存储了对引用的引用,因此,闭包不需要
query
的所有权

现在,闭包捕获了对局部变量的引用,函数试图返回该闭包的所有权

修复方法很简单:将
move
添加到闭包中,以便捕获
query
的副本

fn search<'a>(query: &'a str, text: &'a str) -> impl Iterator<Item=&'a str> {
   text.lines().filter(move |&line| line.contains(query))
}
fn搜索{
text.lines().filter(移动|&行|行.包含(查询))
}

有额外的
->
输入错误guess@KamilCuk哦,是的,你是对的。修好了
fn search<'a>(query: &'a str, text: &'a str) -> impl Iterator<Item=&'a str> {
   text.lines().filter(move |&line| line.contains(query))
}