rustHow to free box memory in Rust
Rust provides a number of ways to free memory.
- Drop: The
drop
function is used to free memory associated with a variable. It is called automatically when a variable goes out of scope.
let x = Box::new(5);
drop(x);
- Manually: Memory can also be manually freed using the
std::mem::drop
function.
let x = Box::new(5);
std::mem::drop(x);
std::mem::forget
: Thestd::mem::forget
function can be used to manually free memory without calling thedrop
function.
let x = Box::new(5);
std::mem::forget(x);
std::mem::replace
: Thestd::mem::replace
function can be used to replace a variable with a new value and free the memory associated with the old value.
let mut x = Box::new(5);
std::mem::replace(&mut x, Box::new(6));
std::mem::swap
: Thestd::mem::swap
function can be used to swap two variables and free the memory associated with the old values.
let mut x = Box::new(5);
let mut y = Box::new(6);
std::mem::swap(&mut x, &mut y);
These functions can be used to free memory in Rust.
Related
More of Rust
- How to use regex to match a double quote in Rust?
- How to replace a capture group using Rust regex?
- How to get an entry from a HashSet in Rust?
- How to match a URL with a regex in Rust?
- How to use regex lookahead in Rust?
- How to match the end of a line in a Rust regex?
- How to replace strings using Rust regex?
- How to split a string by regex in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to use regex with bytes in Rust?
See more codes...