Skip to content

Instantly share code, notes, and snippets.

@pjhades
Created March 10, 2018 16:31
Show Gist options
  • Save pjhades/516fc67cd18eed2f26624f96db3e0476 to your computer and use it in GitHub Desktop.
Save pjhades/516fc67cd18eed2f26624f96db3e0476 to your computer and use it in GitHub Desktop.
se std::{mem, ptr};
fn swap_ptr(p1: &mut *mut Vec<i32>, p2: &mut *mut Vec<i32>) {
let mut p3: *mut Vec<i32> = ptr::null_mut();
p3 = *p1;
*p1 = *p2;
*p2 = p3;
}
fn main() {
let mut v1 = vec![1, 2, 3];
let mut v2 = vec![4, 5, 6];
println!("v1 at {:p}", &v1);
println!("v2 at {:p}", &v2);
let mut p1: *mut Vec<i32> = &mut v1;
let mut p2: *mut Vec<i32> = &mut v2;
println!("before swap");
println!("p1={:p}", p1);
println!("p2={:p}", p2);
let mut p3: *mut Vec<i32> = ptr::null_mut();
p3 = p1;
p1 = p2;
p2 = p3;
println!("swap directly");
println!("p1={:p}", p1);
println!("p2={:p}", p2);
swap_ptr(&mut p1, &mut p2);
println!("swap with function");
println!("p1={:p}", p1);
println!("p2={:p}", p2);
unsafe { (*p1).push(4); }
println!("v1: {:?}", v1);
println!("v2: {:?}", v2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment