013 the type conversion of the book of the dead

Time:2021-4-21

introduce

The video recorded in this series is mainly on station BRust necromancer learning video

Rust necromancer related source information ingithub.com/anonymousGiga/Rustonomi…

Type conversion

Consider an example:

struct Foo {
    a: i32,
    b: i32,
}

struct Bar {
    a: i32,
    b: i32,
}

fn main() {
    let f = Foo{a: 1, b: 2};
    //let _b: Bar = f;

    let _b: Bar = Bar{a: f.a, b: f.b};
    //let _b: Bar = Bar{a: f.a, b: f.b};
    let b = unsafe {&*(&f as *const Foo as * const Bar) };
    println!("b = {:#?}", b);
}

Note: even if the internal data is the same, it can’t be converted directly. If you want to convert, first convert to pointer type, then convert to target pointer type and dereference to target type.

Force type conversion

When converting, the type will be weakened. For example:

&Mut to & T

Special note: cast will not occur when matching a trait (except for receiver, see below for details). That is to say, if a trait is implemented for u, t can be cast to u. it is not considered that t also implements the trait.

trait Trait {}

fn foo<X: Trait>(t: X) {}

impl<'a> Trait for &'a i32 {}

fn main() {
    let t: &mut i32 = &mut 0;
    Foo (T); // an error is reported here. The conversion of & mut I32 to I32 does not mean that the & mut I32 page implements the trait.
}

This work adoptsCC agreementReprint must indicate the author and the link of this article

Linghu Yichong