Created
July 10, 2017 11:09
-
-
Save willmurphyscode/1a99757dcb3b26f67cd004fafbf6fc9a to your computer and use it in GitHub Desktop.
This is shows the difference in Move behavior between a boxed struct whose members can be copied and a box struct whose members can't be copied.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// THANKS TO https://rustbyexample.com/std/box.html | |
// for the code that was modified into this example | |
struct Point { | |
x: f64, | |
y: f64, | |
} | |
struct Rectangle { | |
p1: Point, | |
p2: Point, | |
} | |
fn origin() -> Point { | |
Point { x: 0.0, y: 0.0 } | |
} | |
fn main() { | |
//make a boxed point and boxed rectangle | |
let boxed_rectangle: Box<Rectangle> = Box::new(Rectangle { | |
p1: origin(), | |
p2: origin() | |
}); | |
let boxed_point: Box<Point> = Box::new(origin()); | |
// we can't destructure the boxed rectangle | |
// let p1 = boxed_rectangle.p1; | |
// let p2 = boxed_rectangle.p2; <------ error: use of moved value 'boxed_rectangle' | |
// instead, we have to dereference the box, then destructure: | |
// required because point can't be copied | |
let unboxed_rectangle = *boxed_rectangle; | |
let p1 = unboxed_rectangle.p1; | |
let p2 = unboxed_rectangle.p2; | |
// ok because `x` and `y` are float-64s, which can be copied | |
let x = boxed_point.x; | |
let y = boxed_point.y; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment