water group learning

Original link: https://www.kirito.info/water-water/

logo.png

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?

 1 2 3 4 5 6 7 8 9
 fn thing_factory ( thingtype : i32 ) -> Box < dyn DoThings > {   
    if thingtype == 1 {   
        return Box :: new ( MyStruct1 {});   
    }   
    if thingtype == 2 {   
        return Box :: new ( MyStruct2 {});   
    }   
    panic ! ()   
}   

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> into box<T + metadate> , right?

Potato: that is written by you yourself as

Cuisine: In fact, return box<T> is box<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 into func(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 mutable

In 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 a fn(Animal)->Ret as the callback,
Because this fn(Animal) -> Ret must be able to handle Dog data. So fn(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 as fn()→Animal

You can think of fn(Animal)→() as fn(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.