Original link: https://www.kirito.info/water-water/
Cloud players, all rely on the experience of group friends and water groups, group friends are too strong!
About Box<dyn Trait>
question:
Here is box<struct> -> box<dyn trait>
, or box<struct -> dyn trait>
, if it is the latter, how do you get the size at runtime?
|
|
Answer box<struct> -> box<dyn trait>
Potato:
Box<dyn Trait> == *mut dyn Trait == *mut T + *const metadata_of::<T as Trait>()
Cuisine: The compiler will automatically wrap
box<T>
intobox<T + metadate>
, right?Potato: that is written by you yourself as
Cuisine: In fact,
return box<T>
isbox<T> as box<dyn trait>
, right?Potato: It should be written
as _
5 Dalang: Rust can do limited implicit conversion, because Rust implicit conversion is very rare, but here are
About Variance
For covariant, contravariant, and invariant related backgrounds, you can read this blog: Rust Subtyping and Variance
Crazy forward to my favorites
κόσμος: Suppose you have a
List<Dog>
, and Dog is a subtype of Animal, you can definitely pass it intofunc(x: List<Animal>)
What happens if
List<Animal>
is modified in this func?animals.clear(); animals.add(new Cat());
You will find that there is a Cat in your
List<Dog>
, which is why you cannot use variant under mutableIn the same way, think of this function as a parameter of another function. A function needs a
callback: fn(Dog)->Ret
, so it should be able to pass afn(Animal)->Ret
as the callback,
Because thisfn(Animal) -> Ret
must be able to handle Dog data. Sofn(Animal)->Ret
<fn(Dog)->Ret
,
And Dog < Animal, so a type construction like a function parameter is contravariant
nicball: You can think of
fn()→Cat
asfn()→Animal
You can think of
fn(Animal)→()
asfn(Cat)→()
So the function is covariant to the return type and contravariant to the parameter type
Or use it as a getter setter
It can be thought of as covariant when reading and contravariant when writing
The mutable data structure can only remain unchanged
dick picture
This article is transferred from: https://www.kirito.info/water-water/
This site is only for collection, and the copyright belongs to the original author.