Created
January 23, 2021 03:42
-
-
Save Shuumatsu/fbd412405d0bb0bdb781afe58d60c96b to your computer and use it in GitHub Desktop.
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 SelfRef { | |
text: String, | |
ptr: *const String, | |
} | |
impl SelfRef { | |
fn new(txt: &str) -> Self { | |
let text = String::from(txt); | |
let mut ret = SelfRef { text, ptr: std::ptr::null() }; | |
let ptr = &ret.text as *const String; | |
ret.ptr = ptr; | |
ret | |
} | |
} | |
fn main() { | |
let mut self_ref_a = SelfRef::new("a"); | |
let mut self_ref_b = SelfRef::new("b"); | |
println!("[self_ref_a] text: {}, text of ptr: {}", self_ref_a.text, unsafe { | |
&*self_ref_a.ptr | |
}); | |
println!("[self_ref_b] text: {}, text of ptr: {}", self_ref_b.text, unsafe { | |
&*self_ref_b.ptr | |
}); | |
std::mem::swap(&mut self_ref_a, &mut self_ref_b); | |
println!("after swap contents at each position..."); | |
println!("[self_ref_a] text: {}, text of ptr: {}", self_ref_a.text, unsafe { | |
&*self_ref_a.ptr | |
}); | |
println!("[self_ref_b] text: {}, text of ptr: {}", self_ref_b.text, unsafe { | |
&*self_ref_b.ptr | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment