我已经多次尝试将内容传递给spawn函数(以创建新线程/任务)并让编译器告诉我这个问题error: cannot capture variable of type "blah blah", which does not fulfill "Send", in a bounded closure。
有没有办法转换类型能够满足“发送”或基于某些规则集固定?
例如,我可以ToStr使用这样的指令轻松实现trait:
#[deriving(ToStr, Rand)]
struct Point {
x: int,
y: int,
}
Run Code Online (Sandbox Code Playgroud)
我可以为Send特征做类似的事情吗?还是“善良”的特质被区别对待?
这是这个问题的一个具体例子 -有什么方法可以克服它吗?
fn create_process_options(cmdinfo: &CmdInfo) -> (ProcessOptions, Option<FileDesc>) {
// ... omitted
}
// "po" is of type std::run::ProcessOptions
let (po, filedesc_opt) = create_process_options(&cmdinfo);
spawn(proc() {
let mut ps = Process::new(cmdinfo.program, cmdinfo.args, po).expect("darn");
ps.finish();
});
Run Code Online (Sandbox Code Playgroud)
编译器错误:
error: cannot capture variable of type `std::run::ProcessOptions<>`, which does not fulfill `Send`, in a bounded closure
let mut process = Process::new(cmdinfo.program, cmdinfo.args, po).expect("darn");
^~
note: this closure's environment must satisfy `Send`
let mut process = Process::new(cmdinfo.program, cmdinfo.args, po).expect("darn");
Run Code Online (Sandbox Code Playgroud)
Send 是一种 rust Kind,你提到的其他东西是Traits。虽然两者都可以用来绑定泛型,但实际上它们是完全不同的。您必须选择加入 Trait,但根据其内容推断类型具有哪些种类 - 除了更改内容外,您无法更改类型的种类。
对于大多数种类,规则是“如果 X 的所有成员都属于种类 Y,则类型 X 属于种类 Y”。
在这种情况下,由于 Send 要求您完成'static,这意味着它们不包含任何非'static引用。由于ProcessOptions包含非静态生命周期Option<&'a Path>,就像 Chris Morgan 在他的评论中详述的那样,ProcessOptions不执行发送。