【问题标题】:In Rust, is there any way to change a struct/type to be "Send"?在 Rust 中,有没有办法将结构/类型更改为“发送”?
【发布时间】:2014-02-07 03:02:25
【问题描述】:

我曾多次尝试将内容传递给 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,
}

我可以为 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&lt;'a&gt;dir: Option&lt;&amp;'a Path&gt; 字段。包含引用的结构不能是Send。剩下的问题是为什么它是&amp;Path 而不是Path。答案似乎是std::io::process::ProcessConfig 主要使用引用,包括可能来自ProcessOptions.dircwd: Option&lt;&amp;str&gt;
  • 好的。感谢您的解释。我可以理解为什么要设置这些限制,但是在尝试进行多线程/任务编程时确实会使其成为地雷。
  • @quux00:实际上,我认为这将是 C++ 中的地雷(因为它有时会在你的脸上爆炸),而在 Rust 中,你得到的只是严厉地拒绝继续。跨度>

标签: rust


【解决方案1】:

Send 是一种锈Kind,你提到的其他东西是Traits。虽然两者都可以用来绑定泛型,但它们实际上是完全不同的。您必须选择加入 Trait,但类型的 Kinds 是根据其内容推断的 - 除了更改内容之外,您无法更改类型的 Kind。

对于大多数种类,规则是“如果 X 的所有成员都属于种类 Y,则类型 X 属于种类 Y。”

在这种情况下,由于发送要求您履行'static,这意味着它们不包含任何非'static 引用。由于 ProcessOptions 包含非静态生命周期 Option&lt;&amp;'a Path&gt;,就像 Chris Morgan 在他的评论中详述的那样,ProcessOptions 不满足发送。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    相关资源
    最近更新 更多