如何确保我的类型实现自动特征?

问题描述 投票:0回答:1

假设我有一个类似的结构:

struct Foo {
  foo: Box<dyn ToString>,
}

Copy
这样的自动特征不同,我无法将
#[derive(Send)
添加到我的结构中以要求编译器选择加入并确保
Send
由我的结构实现。

我可以选择什么来确保我的类型实现,例如

Send

rust traits
1个回答
0
投票

这个问题已在 Rust 的 用户论坛 上提出。结论是没有真正的好方法来做到这一点。这是像

Send
这样的自动特征的弱点,它不像
Copy
那样可以选择加入。

我发现的唯一方法是简单地使用需要自动特征的泛型,并尝试将您的类型与它一起使用:

#[cfg(test)]
mod tests {
  use crate::Foo;

  fn test_send<T: Send>() {}

  #[test]
  fn foo_must_be_send() {
    test_send::<Foo>();
  }
}
error[E0277]: `(dyn ToString + 'static)` cannot be sent between threads safely
   --> src/lib.rs:13:17
    |
13  |     test_send::<Foo>();
    |                 ^^^ `(dyn ToString + 'static)` cannot be sent between threads safely

它远非完美,但至少它会确保你的类型是发送,如果你正在做公共API。

© www.soinside.com 2019 - 2024. All rights reserved.