Skip to content

Instantly share code, notes, and snippets.

@matthiasg
Forked from rust-play/playground.rs
Last active March 21, 2019 10:42
Show Gist options
  • Save matthiasg/0838b6ef2a32d2d5ce70aec2b35f6925 to your computer and use it in GitHub Desktop.
Save matthiasg/0838b6ef2a32d2d5ce70aec2b35f6925 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
struct MyType {
value: u32
}
impl MyType {
fn new() -> MyType {
MyType {
value: 1
}
}
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 = MyType::new();
// 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 = MyType::new();
// 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 = MyType::new();
// 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