In unsafe code, the use of the modules std::mem (which contains functions to work with memory at a low level) and std::ptr (which contains functions to work with raw pointers) is common, as we saw with std::mem::transmute.
Here are some more examples.
To swap two variables by explicitly using pointers, use std::mem::swap like this:
// code from Chapter 10/code/swap.rs: use std::mem; fn main() { let mut n = 0; let mut m = 1; mem::swap(&mut n, &mut m); println!("n: {} m: {}", n, m); }
This prints out the following:
n: 1 m: 0
As another example, the mem::size_of_val() function from the mem module takes a reference to a value and returns the number of bytes it occupies in memory. mem::size_ of returns the size of the given type in bytes as a u8. For an example of its use, see the following code:
// code from Chapter 10/code/size_of_val.rs: use std::mem; fn main() { let arr = ["Rust", "Go", "Swift"]; println!("array arr occupies {} bytes", mem::size_of_val(&arr)); println!("The size of an isize: {} bytes", mem::size_of::<isize>()); }
This prints out the following:
array arr occupies 48 bytes The size of an isize: 8 bytes