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

时间:2016-12-22 09:20:50

标签: rust closures lifetime

我正在编写一个简单的程序,它可以遍历目录,读取其条目并生成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) {
   |

2 个答案:

答案 0 :(得分:1)

问题

如果仔细查看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)
}

解决方案2:按值

返回闭包

虽然这在稳定的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
}

答案 1 :(得分:1)

经过几天的摸索,我认为我找到了一个解决方案,利用Boxmovemove + Box不创建深层克隆)。

但它并不是我想要的,因为我必须更改visit_dirs签名(这段代码是从rust doc复制的,所以我不想改变它)。如果有人有更好的建议,请告诉我。

到@ker&amp; @aochagavia,感谢您的帮助,真的很感激。

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<'a>(docs: &'a mut Vec<Doc>) -> Box<FnMut(&DirEntry) + 'a> {
        let handler = move |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)
    }

    {
        let mut handler = create_handler(&mut docs);
        visit_dirs(&target_path, &mut |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: &mut FnMut(&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(())
}