I have an factory-method constructor like this:
impl dyn Transport {
pub fn new(s: &str) -> Result<Box<dyn Transport>> {
// Imagine in the future this returns various impls depending on `s`
Ok(Box::new(local::LocalTransport::new(&Path::new(s))))
}
}
With rustc 1.53.0-nightly (07e0e2ec2 2021-03-24) I now get a warning
|
248 | let transport = Transport::new(&temp.path().to_string_lossy()).unwrap();
| ^^^^^^^^^ help: use `dyn`: `<dyn Transport>`
warning: trait objects without an explicit `dyn` are deprecated
I can understand how to change it to <dyn Transport>::new(...)
- in fact rust-analyzer suggests the change for me, which is awesome. But this makes the calling code rather ugly.
I can also understand, I think, why in general Rust is moving towards requiring an explicit dyn
on use of trait objects.
My questions are:
-
Why is a
dyn
recommended here? As far as I can see the call toTransport::new
is not going through a vtable or fat pointer or in any sense dynamic. -
Is this a signal that this is not a natural rustic way to write an abstract constructor? What would be better? (The obvious step would be to move it to an unassociated function.)