gpt4 book ai didi

rust - 返回一个改变其环境的闭包

转载 作者:行者123 更新时间:2023-11-29 08:00:29 24 4
gpt4 key购买 nike

我正在编写一个简单的程序来遍历一个目录,读取它的条目并生成一个 JSON 结构。当我试图返回一个改变捕获的 &mut Vec 参数的闭包时,我遇到了麻烦:

use std::io;
use std::fs::{self, DirEntry,};
use std::path::Path;

extern crate rustc_serialize;
use rustc_serialize::json;


// json encoding:
#[derive(Debug, RustcEncodable)]
struct Doc {
path: String,
filename: String,
}


fn main() {
let target_path = Path::new("/Users/interaction/workspace/temp/testeddocs");
let mut docs: Vec<Doc> = Vec::new();

fn create_handler(docs: &mut Vec<Doc>) -> &FnMut(&DirEntry) {
let handler = |entry: &DirEntry| -> () {
let doc = Doc {
path: entry.path().to_str().unwrap().to_string(),
filename: entry.file_name().into_string().unwrap(),
};
docs.push(doc);
};

&handler
}
{
let handler = create_handler(&mut docs);
visit_dirs(&target_path, & |entry: &DirEntry|{
handler(entry);
});
}
println!("result json is: {}", json::encode(&docs).unwrap());
}

// one possible implementation of walking a directory only visiting files
fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<()> {
if try!(fs::metadata(dir)).is_dir() {
for entry in try!(fs::read_dir(dir)) {
let entry = try!(entry);
if try!(fs::metadata(entry.path())).is_dir() {
try!(visit_dirs(&entry.path(), cb));
} else {
cb(&entry);
}
}
}
Ok(())
}

这是它给出的编译器错误:

error: cannot borrow immutable borrowed content `***handler` as mutable
--> src/main.rs:36:13
|
36 | handler(entry);
| ^^^^^^^

error[E0373]: closure may outlive the current function, but it borrows `docs`, which is owned by the current function
--> src/main.rs:23:23
|
23 | let handler = |entry: &DirEntry| -> () {
| ^^^^^^^^^^^^^^^^^^^^^^^^ may outlive borrowed value `docs`
...
28 | docs.push(doc);
| ---- `docs` is borrowed here
|
help: to force the closure to take ownership of `docs` (and any other referenced variables), use the `move` keyword, as shown:
| let handler = move |entry: &DirEntry| -> () {

error: `handler` does not live long enough
--> src/main.rs:31:10
|
31 | &handler
| ^^^^^^^ does not live long enough
32 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the block at 22:64...
--> src/main.rs:22:65
|
22 | fn create_handler(docs: &mut Vec<Doc>) -> &FnMut(&DirEntry) {
|

最佳答案

问题

如果仔细查看 create_handler,您会发现 handler 将在函数结束时被销毁,因为它只是一个局部变量。因此,Rust 禁止任何可能从函数外部使用的对 handle 的引用。否则,引用将指向不再可用的数据(经典的悬挂指针错误)。

解决方案 1:装箱闭包

您可以通过装箱(在堆上分配)将闭包作为特征对象返回。这是在稳定的 Rust (1.14) 中执行此操作的唯一方法:

fn create_handler(docs: &mut Vec<Doc>) -> Box<FnMut(&DirEntry)> {
let handler = |entry: &DirEntry| -> () {
let doc = Doc {
path: entry.path().to_str().unwrap().to_string(),
filename: entry.file_name().into_string().unwrap(),
};
docs.push(doc);
};

Box::new(handler)
}

方案二:按值返回闭包

虽然这在稳定的 Rust (1.14) 中不起作用,但您可以在夜间使用它。这种方法的好处是它避免了堆分配:

fn create_handler(docs: &mut Vec<Doc>) -> impl FnMut(&DirEntry) {
let handler = |entry: &DirEntry| -> () {
let doc = Doc {
path: entry.path().to_str().unwrap().to_string(),
filename: entry.file_name().into_string().unwrap(),
};
docs.push(doc);
};

handler
}

关于rust - 返回一个改变其环境的闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41279626/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com