Beginner Question about struct

It is from Rust by example's activities. The complier said "error[E0382]: use of moved value: point". I have tried to pass by reference and deref but got other error.
It seems "top_left: point" has moved ownership. I don't know how to make it works.

// An attribute to hide warnings for unused code.
#![allow(dead_code)]

// A struct with two fields
struct Point {
    x: f32,
    y: f32,
}

// Structs can be reused as fields of another struct
struct Rectangle {
    // A rectangle can be specified by where the top left and bottom right
    // corners are in space.
    top_left: Point,
    bottom_right: Point,
}

fn main() {
    // Instantiate a `Point`
    let point: Point = Point { x: 10.3, y: 0.4 };

    // Access the fields of the point
    println!("point coordinates: ({}, {})", point.x, point.y);

    fn square(point: Point, w: f32) -> Rectangle {
        Rectangle {
            top_left: point,
            bottom_right: Point {
                x: point.x + w,
                y: point.y - w,
            },
        }
    }

    let rect = square(point, 0.2);

    println!(
        "({},{}) ({},{})",
        rect.top_left.x, rect.top_left.y, rect.bottom_right.x, rect.bottom_right.y
    );
}

Multiple ways to make your code work

  1. Rust Playground
    Rectangle {
            bottom_right: Point { // copy fields in point
                x: point.x + w,
                y: point.y - w,
            },
            top_left: point, // put it down to consume point
        }
  1. Rust Playground
#[derive(Clone, Copy)] // make Point Copy
struct Point { ... }
  1. Rust Playground
        let bottom_right = Point {
            x: point.x + w,
            y: point.y - w,
        }; // Like 1: copy fields 
        Rectangle {
            top_left: point, // and consume point
            bottom_right,
        }
4 Likes

So from your reply, i guess the question is that the struct Point without trait Copy, so faced with the code "top_left: point", the point's owner is moved to top_left , so point can't be use anymore. Is my understanding right?

Yes. But the key point is ownership: use the shared/exclusive reference(s) to an owned value whenever possible before the ownership is consumed. Copy is not a magic: you implicitly get an ownership copy when the ownership is needed.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.