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

后端 未结 2 1807
滥情空心
滥情空心 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:10

    What really happens

    fn main() {
        let mut point: Point = Point { x: 0.3, y: 0.4 };
        println!("point coordinates: ({}, {})", point.x, point.y);
    
        drop(point);
    
        {
            let mut point: Point;
            point.x = 0.5;
        }
    
        println!(" x is {}", point.x);
    }
    

    It turns out that it's already known as issue #21232.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题