Created
November 8, 2018 05:44
-
-
Save kannapoix/e379bff7eba948dba3340d6742fb7948 to your computer and use it in GitHub Desktop.
rust mutability
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
#[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