Reputation: 30212
I am trying to implement a Doubly Linked List for fun in Rust.
I faced an issue with the ownership system, the inability to alias two pointers. I realize the benefits of pointer aliasing, but I'd like to make an exception this time.
I'd like to know if there is any way to have two *mut A
pointers pointing to the same memory address.
For example, right now I have this:
self.first = unsafe { mem::transmute(new_node) };
// How do I set self.last to point at the same new_node?
I am aware of Rc
and RefCell
types, but I'd like to avoid using them in data structures as they have run-time overhead.
Upvotes: 0
Views: 1368
Reputation: 430634
While I agree with dbaupp that you should provide more context because this isn't what you should do, here's the answer to the exact question you asked:
fn main() {
let mut a: u32 = 42;
let b: *mut u32 = &mut a;
let c: *mut u32 = &mut a;
println!("{:?}, {:?}", b, c);
}
Now you have two *mut u32
pointers pointing at the same memory address. And without unsafe
! Of course, if you want to use the pointers, you now have to do a lot more thinking to decide if you've completely broken all the assumptions and guarantees that the compiler expects! :-)
Upvotes: 2
Reputation: 38576
I'm not sure exactly what you mean. &mut
is the one that has the aliasing enforcing. *mut
can be copied like anything else, dereferencing a raw pointer of course is unsafe
, but you should be able to do this:
fn main() {
let mut x: i32 = 5i32;
let xptr: *mut i32 = &mut x as *mut i32;
let xptr_copy: *mut i32 = xptr;
unsafe {
println!("xptr: {}", *xptr);
println!("xptr_copy: {}", *xptr_copy);
}
}
Upvotes: 1