One reason unsafe Rust exists because the underlying computer hardware is inherently unsafe.
Other reason, Rust needs to allow programmer to interact with the operating system.
Other goal of the Rust programming language to allow software engineer to work with low-level programming.
Rust has type called pointer.
Programmers can create pointers.
Use "as" to cast a reference mutable variable into their corresponding pointer type.
Change or print pointers in the unsafe block.
Example: Rust pointers
Here's the Rust program that implements a pointer using reference ampersand symbol for mutable keyword, variable name, "as" casting, pointer asterisk symbol for mutable keyword again, and data type name.
fn main() {
let mut i = 10;
let ptr_to_i = &mut i as *mut i32;
unsafe {
*ptr_to_i = 20;
println!("*ptr_to_i: {}", *ptr_to_i);
}
// variable i is changed by the pointer
println!("i: {}", i);
}
No comments:
Post a Comment