Last active
May 10, 2019 15:07
-
-
Save wilspi/0e17b42879e6c9e782160ff7f3e1e783 to your computer and use it in GitHub Desktop.
Rust - abnormal behaviour - dangling reference
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
#[derive(Debug)] | |
pub enum Superheroes { | |
Superman(Superman), | |
Batman(Batman) | |
} | |
#[derive(Debug)] | |
pub struct Superman { | |
id: i32, | |
name: String, | |
origin: String | |
} | |
#[derive(Debug)] | |
pub struct Batman { | |
id: i32, | |
name: String, | |
} | |
fn main() { | |
let mut a = Superman { | |
id: 1, | |
name: "Kal-El".to_string(), | |
origin: "Krypton".to_string() | |
}; | |
let mut s_man = Superheroes::Superman(a); | |
let rf = match s_man { | |
Superheroes::Superman(ref mut p) => p, | |
_ => unimplemented!(), | |
}; | |
rf.name = "Clark Kent".to_string(); | |
println!("Printing rf.name: {:#?}", rf.name); | |
match s_man { | |
Superheroes::Superman(mut p) => { | |
// Updating p | |
p.name = "Superman".to_string(); | |
println!("p.name: {:#?}", p.name); | |
// Updating rf | |
println!("rf.name: {:#?}", rf.name); | |
rf.name = "Shaktimaan".to_string(); | |
println!("rf.name: {:#?}", rf.name); | |
// Value of p | |
println!("p.name: {:#?}", p.name); | |
}, | |
_ => unimplemented!(), | |
} | |
println!("Printing rf here: {:#?}", rf); | |
// Here s_man is not accessible, uncommenting following gives err | |
// println!("Printing s_man here: {:#?}", s_man); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
rust toolchain 1.34.0-x86_64-apple-darwin
cargo edition 2015
cargo edition 2018