Created
March 21, 2019 10:30
-
-
Save rust-play/763476aa57c2109b23241160c1ccd422 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or 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 MyType { | |
value: u32 | |
} | |
fn new_type() -> MyType { | |
MyType { | |
value: 1 | |
} | |
} | |
impl MyType { | |
fn mv_immutable(self) {} | |
fn mv_mutable(mut self) { | |
self.value = 2; | |
} | |
fn ref_immutable(&self) {} | |
fn ref_mutable(&mut self) { | |
self.value = 3; | |
} | |
} | |
fn main() { | |
// create owned value and store in `a` | |
let a = MyType{ value:3 }; | |
// destroy `a` by moving its value into its `mv_immutable` function | |
a.mv_immutable(); | |
// create owned value and store it in `b` | |
let b = new_type(); | |
// destroy `b` by moving its value mutably into the `mv_mutable` function | |
// note that `b` isn't `mut`, it doesn't need to be; since there can only be one owner of a value, | |
// we can make the value mutable as it is moved | |
b.mv_mutable(); | |
// create owned value and store in `c` | |
let c = new_type(); | |
// pass an immutable reference to the its `ref_immutable` function | |
c.ref_immutable(); | |
c.ref_immutable(); | |
// create owned value and store it in `d` | |
let mut d = new_type(); | |
// pass a mutable reference to its `ref_mutable` function | |
d.ref_mutable(); | |
d.ref_mutable(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment