Welcome back, dear learner! Today, we're diving into one of Rust's powerful features: Raw Pointers. These pointers are crucial for low-level programming and understanding them will take your Rust skills to the next level. Let's get started!
Raw pointers in Rust are used to directly manipulate memory, bypassing the ownership and borrowing rules. There are two types of raw pointers: *const T and *mut T.
š” Pro Tip: T here is the data type that the pointer is pointing to.
*const T is a pointer that points to a constant value. Once assigned, the value can't be changed.
const MESSAGE: &str = "Hello, World!";
let pointer: *const str = MESSAGE as *const str;
// It's not possible to modify the content of pointer
// let mutable_message = unsafe { &mut *pointer }; // Error
println!("{}", unsafe { *pointer });In this example, we create a constant string MESSAGE and convert it into a *const str pointer. After that, we print the content of the pointer, which is the original MESSAGE string.
*mut T is a mutable raw pointer that can change the value it points to.
let mut data: i32 = 42;
let raw_data: *mut i32 = &mut data as *mut i32;
// Modifying the value through the raw pointer
unsafe {
*raw_data = 100;
}
println!("{}", data); // Output: 100In this example, we create an i32 variable data and convert it into a *mut i32 pointer. After that, we modify the value through the raw pointer and print the updated value.
š Note: Working with raw pointers is dangerous because they bypass Rust's safety mechanisms. Always use them carefully and only when necessary.
What is the purpose of a `*const T` raw pointer in Rust?
That's it for today! With raw pointers, you can access and manipulate memory directly in Rust. In the next lesson, we'll dive deeper into the safety mechanisms and learn how to handle raw pointers safely.
Stay curious and happy coding! šÆ š” š ā