From cce6a8ae0cffd5d99e90354e8820532ca9e9981d Mon Sep 17 00:00:00 2001 From: Chris Krycho Date: Thu, 3 Oct 2024 08:24:47 -0600 Subject: [PATCH] Use new `&raw` feature for sound raw pointer usage. Note: this requires Rust 1.82.0. --- listings/ch20-advanced-features/listing-20-01/src/main.rs | 4 ++-- listings/ch20-advanced-features/listing-20-03/src/main.rs | 4 ++-- src/ch20-01-unsafe-rust.md | 7 +++++++ 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/listings/ch20-advanced-features/listing-20-01/src/main.rs b/listings/ch20-advanced-features/listing-20-01/src/main.rs index 893f578905..492b43ba3b 100644 --- a/listings/ch20-advanced-features/listing-20-01/src/main.rs +++ b/listings/ch20-advanced-features/listing-20-01/src/main.rs @@ -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 } diff --git a/listings/ch20-advanced-features/listing-20-03/src/main.rs b/listings/ch20-advanced-features/listing-20-03/src/main.rs index 02a0be6b0e..6ed8ca2afc 100644 --- a/listings/ch20-advanced-features/listing-20-03/src/main.rs +++ b/listings/ch20-advanced-features/listing-20-03/src/main.rs @@ -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); diff --git a/src/ch20-01-unsafe-rust.md b/src/ch20-01-unsafe-rust.md index 4aadf82d83..794f4b1d0b 100644 --- a/src/ch20-01-unsafe-rust.md +++ b/src/ch20-01-unsafe-rust.md @@ -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. + + 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 @@ -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. + + 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