Unsafe functions and blocks

Let's look at unsafe functions and blocks, starting with unsafe functions:

// unsafe_function.rsfn get_value(i: *const i32) -> i32 {     *i}fn main() {    let foo = &1024 as *const i32;    let _bar = get_value(foo);}

We defined a get_value function that takes in a pointer to an i32 value, which simply returns the pointed value back by dereferencing it. In main, we are passing foo to get_value, which is a reference to an i32 value that 1024 cast to *const i32. If we try running this, the compiler says the following:

As we already said, we need an unsafe function or block to dereference a raw pointer. Let's go with the first ...

Get The Complete Rust Programming Reference Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.