Rust, Raw Pointer

Mike Code
1 min readMar 19, 2024

--

Raw pointer is similar to reference, can be mutable or immutable, immutable type : *const T, mutable type : *mut T ( * is not dereference operator, it’s part of the type name);

Differences from reference:

1Allow to ignore the borrowing rules, can have multiple mutable pointers or both mutable and immutable pointers at same time to same location.

2 Not guaranteed to point to a valid memory.

3Allow to be null

4Not implement any automatic cleanup

fn main() {
let mut a = 5;
let b = &a as *const i32;
let c = &mut a as *mut i32;
}

To create two raw pointers. We can create raw pointers not within unsafe block, but we can’t dereference them not in the unsafe block. We use as to typecast from reference type into raw pointer.

So we dereference raw pointer within unsafe block by using dereference operator * (asterisk sign)

unsafe {
println!("{}", *b);
println!("{}", *c)
}

--

--