我曾多次遇到这样的问题,即尝试将东西传递给
spawn
函数(创建新线程/任务),却被编译器告知 error: cannot capture variable of type "blah blah", which does not fulfill "Send", in a bounded closure
。
有没有一种方法可以使类型满足 "Send" 的要求,还是它们已经固定在某些规则上了?
例如,我可以轻松地通过使用类似以下指令来实现 ToStr
trait:#[deriving(ToStr, Rand)]
struct Point {
x: int,
y: int,
}
我能否为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();
});
编译器错误:
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");
ProcessOptions<'a>
结构体中的dir: Option<&'a Path>
字段。包含引用的结构体不能被标记为Send
。剩下的问题是为什么是&Path
而不是Path
。答案似乎是std::io::process::ProcessConfig
主要使用引用,包括cwd: Option<&str>
,它可能来自于ProcessOptions.dir
。 - Chris Morgan