What is the usage of pointers in the Rust language?
In Rust language, there are several ways to use pointers.
- Regular pointers in Rust are created using the & symbol. References allow for borrowing the ownership of data, but do not allow for modifying the data. There are two types of references: mutable references and immutable references.
- x is initialized to 5.
y is a reference to x with the immutability property.
z is initialized to 10.
w is a mutable reference to z. - Raw Pointers: In Rust, raw pointers are pointers that are not subject to safety checks and are typically used for low-level operations. They can be declared using *const T for immutable raw pointers and *mut T for mutable raw pointers.
- x is assigned the value of 5.
raw_ptr is a constant raw pointer to x.
y is assigned the value of 10.
mut_raw_ptr is a mutable raw pointer to y. - When using raw pointers, you need to wrap the code block in the “unsafe” keyword to indicate that the operations in that code block are not subject to Rust’s safety checks.
- Box pointer: By using the Box
type, memory can be allocated on the heap and automatically released when it is destroyed. - Create a new box containing the value 5 and assign it to the variable x.
- Box pointers are typically used to create dynamically allocated data structures in situations where ownership transfer is needed.
Additionally, Rust also offers other types of pointers, such as null and const versions of raw pointers (std::ptr::null and std::ptr::null_mut), as well as pointers of std::os::raw::c_void type for manipulating native operating system handles.