【发布时间】:2017-03-12 12:51:09
【问题描述】:
我需要一个闭包来引用其封闭环境中的对象的一部分。对象是在环境中创建的,并且作用于它,但是一旦创建它就可以安全地移动到闭包中。
用例是一个执行一些准备工作并返回一个闭包的函数,该闭包将完成其余的工作。这种设计的原因是执行约束:第一部分工作涉及分配,其余部分必须不进行分配。这是一个最小的例子:
fn stage_action() -> Box<Fn() -> ()> {
// split a freshly allocated string into pieces
let string = String::from("a:b:c");
let substrings = vec![&string[0..1], &string[2..3], &string[4..5]];
// the returned closure refers to the subtrings vector of
// slices without any further allocation or modification
Box::new(move || {
for sub in substrings.iter() {
println!("{}", sub);
}
})
}
fn main() {
let action = stage_action();
// ...executed some time later:
action();
}
这无法编译,正确说明&string[0..1] 和其他人不得超过string。但是如果将string 移到闭包中,就没有问题了。有没有办法强制这种情况发生,或者有另一种方法可以让闭包引用在它之外创建的对象的一部分?
我还尝试创建具有相同功能的struct 以使移动完全明确,但doesn't compile either。同样,编译失败,错误为&later[0..1] 和其他人只能活到函数结束,但是“借用的值必须在静态生命周期内有效”。
即使completely avoiding a Box 似乎也无济于事 - 编译器抱怨该对象的寿命不够长。
【问题讨论】:
标签: rust