Why does compilation not fail when a member of a moved value is assigned to?

后端 未结 2 1816
滥情空心
滥情空心 2020-11-30 12:49

I am working through examples in Rust by Example.

#[derive(Debug)]
struct Point {
    x: f64,
    y: f64,
}

#[derive(Debug)]
struct Rectangle {
    p1: Poin         


        
2条回答
  •  醉话见心
    2020-11-30 13:32

    The problem is that the compiler allows partial reinitialization of a struct, but the whole struct is unusable after that. This happens even if the struct contains only a single field, and even if you only try to read the field you just reinitialized.

    struct Test {
        f: u32,
    }
    
    fn main() {
        let mut t = Test { f: 0 };
        let t1 = t;
        t.f = 1;
        println!("{}", t.f);
    }
    

    This is discussed in issue 21232

提交回复
热议问题