0

This code:

let mut a2 = 99;
let b: *mut i32 = &mut a2;
*b = 11; // does not compile , even after unsafe {*b}

Generates the error:

error[E0133]: dereference of raw pointer requires unsafe function or block
 --> src/main.rs:4:5
  |
4 |     *b = 11;
  |     ^^^^^^^ dereference of raw pointer

But this code works:

let mut a2 = 99
let b = &mut a2;
*b = 11;

What is the difference between the two?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
soupybionics
  • 4,200
  • 6
  • 31
  • 43
  • What's wrong with `unsafe {}`? Maybe you put it in the wrong place? https://play.rust-lang.org/?gist=388da28b6bfac187a3c0ec12e1798246&version=stable – loganfsmyth Dec 18 '17 at 18:51

1 Answers1

5

What is the difference between the two?

One is a raw pointer (*mut _) and the other is a reference (&mut _). As the book says:

the compiler guarantees that references will never be dangling

Additionally, a reference will never be NULL. It is always safe to dereference a reference. It is not always safe to dereference a raw pointer as the compiler cannot guarantee either of those. Thus, you need an unsafe block:

unsafe { *b = 11; }

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366