Last active
December 16, 2015 17:29
-
-
Save grahamking/5470560 to your computer and use it in GitHub Desktop.
Rust: The pointer and the box it points to
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
struct Point { x: int, y:int } | |
fn main() { | |
// Local variable, easy | |
let mut p1 = Point{x:1, y:2}; | |
p1.x = 10; | |
// Owned pointer | |
// also easy because target inherts mutability | |
let mut p2 = ~Point{x:1, y:2}; | |
p2.x = 10; | |
// Managed pointer | |
// Not so easy. This won't work | |
let mut pNO = @Point{x:1, y:2}; | |
pNO.x = 10; // You could change pNO, but not pNO.x | |
// Need to make the contents mutable. | |
// Do not need to make the variable | |
// itself mutable - you can | |
// change p.x, but not p. | |
let p3 = @mut Point{x:1, y:2}; | |
p3.x = 10; | |
println(fmt!("%d, %d, %d", p1.x, p2.x, p3.x)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment