November 2017
Intermediate to advanced
264 pages
5h 45m
English
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 ...
Read now
Unlock full access