Skip to content

Instantly share code, notes, and snippets.

@kannapoix
Created November 8, 2018 05:44
Show Gist options
  • Save kannapoix/e379bff7eba948dba3340d6742fb7948 to your computer and use it in GitHub Desktop.
Save kannapoix/e379bff7eba948dba3340d6742fb7948 to your computer and use it in GitHub Desktop.
rust mutability
#[derive(Debug)]
struct Parent {
child: Child,
}
#[derive(Debug)]
struct Child {
name: String,
}
fn main() {
println!("Hello, world!");
non_mutable();
mutable_parent();
}
fn non_mutable() {
let child = Child {
name: String::from("Alice"),
};
let parent = Parent {
child: child,
};
// println!("{:#?}", parent);
// parent.child_one.name = String::from("Carol")
// cannot mutably borrow field of immutable binding
}
fn mutable_child() {
let mut mut_child = Child {
name: String::from("Alice"),
};
let parent = Parent {
child: mut_child,
};
// println!("{:#?}", parent);
// parent.child.name = String::from("Carol")
// cannot mutably borrow field of immutable binding
}
fn mutable_parent() {
let child = Child {
name: String::from("Alice"),
};
let mut parent = Parent {
child: child,
};
println!("{:#?}", parent);
// return
// Parent {
// child: Child {
// name: "Alice"
// }
// }
parent.child.name = String::from("Carol");
println!("{:#?}", parent);
// return
// Parent {
// child: Child {
// name: "Carol"
// }
// }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment