Skip to content

Commit

Permalink
Use new &raw feature for sound raw pointer usage.
Browse files Browse the repository at this point in the history
Note: this requires Rust 1.82.0.
  • Loading branch information
chriskrycho committed Oct 3, 2024
1 parent 8f1ef1e commit cce6a8a
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 4 deletions.
4 changes: 2 additions & 2 deletions listings/ch20-advanced-features/listing-20-01/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ fn main() {
// ANCHOR: here
let mut num = 5;

let r1 = &num as *const i32;
let r2 = &mut num as *mut i32;
let r1 = &raw const num;
let r2 = &raw mut num;
// ANCHOR_END: here
}
4 changes: 2 additions & 2 deletions listings/ch20-advanced-features/listing-20-03/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ fn main() {
// ANCHOR: here
let mut num = 5;

let r1 = &num as *const i32;
let r2 = &mut num as *mut i32;
let r1 = &raw const num;
let r2 = &raw mut num;

unsafe {
println!("r1 is: {}", *r1);
Expand Down
7 changes: 7 additions & 0 deletions src/ch20-01-unsafe-rust.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,11 @@ Notice that we don’t include the `unsafe` keyword in this code. We can create
raw pointers in safe code; we just can’t dereference raw pointers outside an
unsafe block, as you’ll see in a bit.

<!--
TODO: rewrite to not use `as` initially, but to show that it is another way to
do it where you *need* to work with integer values directly instead.
-->

We’ve created raw pointers by using `as` to cast an immutable and a mutable
reference into their corresponding raw pointer types. Because we created them
directly from references guaranteed to be valid, we know these particular raw
Expand Down Expand Up @@ -136,6 +141,8 @@ dereference operator `*` on a raw pointer that requires an `unsafe` block.
Creating a pointer does no harm; it’s only when we try to access the value that
it points at that we might end up dealing with an invalid value.

<!-- TODO: again, update this to account for using `&raw` -->

Note also that in Listing 20-1 and 20-3, we created `*const i32` and `*mut i32`
raw pointers that both pointed to the same memory location, where `num` is
stored. If we instead tried to create an immutable and a mutable reference to
Expand Down

0 comments on commit cce6a8a

Please sign in to comment.