Skip to content

Instantly share code, notes, and snippets.

@wilspi
Last active May 10, 2019 15:07
Show Gist options
  • Save wilspi/0e17b42879e6c9e782160ff7f3e1e783 to your computer and use it in GitHub Desktop.
Save wilspi/0e17b42879e6c9e782160ff7f3e1e783 to your computer and use it in GitHub Desktop.
Rust - abnormal behaviour - dangling reference
#[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);
}
@wilspi
Copy link
Author

wilspi commented May 9, 2019

rust toolchain 1.34.0-x86_64-apple-darwin

Screenshot 2019-05-09 at 3 04 53 PM

cargo edition 2015

Screenshot 2019-05-09 at 4 04 43 PM

cargo edition 2018

Screenshot 2019-05-09 at 4 05 46 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment