Let’s say I have a struct like:
struct Foo {
foo: Box<dyn ToString>,
}
Unlike auto-trait like Copy
that are opt-in I can’t add #[derive(Send)
to my struct to ask the compiler to opt-in and ensure Send
is implemented by my structure.
What are my option to ensure my type implement for example Send
?
This question have been raise on the user forum on Rust. The conclusion is there is not really a good way to do this. It’s a weakness of auto-trait like Send
that are not opt-in like Copy
.
The only way I found is to simply use a generic that require the auto-trait, and try to use your type with it:
#[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
It’s far from perfect but at least it will ensure your type is Send if you are doing public API.