What is the difference between impl trait
and box & lt; DYN Trait & gt;
? Are they interchangeable?
Let’s say … there is such a code:
trait animal {
Fn Noise (& amp; self);
}
Struct Sheep;
impl animal for sheep {
Fn Noise (& amp; self) {
PrintLN! ("Beeeeh");
}
}
fn get_sheep_one () - & gt; impl animal {
Sheep {}
}
fn get_sheep_two () - & gt; Box & lt; Dyn Animal & GT; {
BOX :: NEW (SHEEP {})
}
FN Main () {
get_sheep_one (). Noise ();
get_sheep_two (). Noise ();
}
Does the difference between the first and second functions lies only in the second case the object type Box
is returned
Answer 1, Authority 100%
The difference is that the exact type of Impl Animal
must be removed at the compilation stage i. fn get_sheep_one () - & gt; Impl Animal
For this implementation is equivalent to the simple return Sheep
.
if you add another type:
struct cow;
impl Animal for COW {
Fn Noise (& amp; Self) - & gt; & amp; 'static str {
"Moooooo!"
}
}
That such a function will no longer work:
fn get_animal_by_str_bad (s: & amp; str) - & gt; Result & lt; impl Animal, String & GT; {
IF S == "COW" {
OK (COW {})
} else if s == "sheep" {
OK (SHEEP {})
} else {
ERR ("Unknown Animal" .to_string ())
}
}
and will give an error [playground] :
error [E0308]: Mismatched Types
- & gt; SRC / Main.RS: 25: 10
|
25 | OK (SHEEP {})
| ^^^^^^^ Expected Struct `Cow`, Found Struct` Sheep`
|
= Note: EXPECTED TYPE `COW`
Found Type `Sheep`
The error text is somewhat confused, but it is such a logic: based on the fact that the first returned value in the course of the text was Cow
, Rust
output that impl Animal
should be like COW
and indignant when after he decided that there would be a cow, she was sent to him.
In order to overcome this restriction, just need to use Box
and DYN
[PlayGround] :
fn get_animal_by_str (s: & amp; str) - & gt; Result & lt; Box & lt; DYN ANIMAL & GT;, String & GT; {
IF S == "COW" {
OK (BOX :: NEW (COW {}))
} else if s == "sheep" {
OK (BOX :: NEW (SHEEP {}))
} else {
ERR ("Unknown Animal" .to_string ())
}
}
In fact, the whole structure means that we return the link to the dynamic object (Box
), which is implementing (this is said about DYN
) ANIMAL
In the original version of the practical difference in general, it is not, except that the option with Box
will have an overwhelming on the selection / release of the memory and the reference to the link. But in essence these are two different actions.