rustHow to free box memory in Rust
Rust provides a number of ways to free memory.
- Drop: The
dropfunction 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::dropfunction.
let x = Box::new(5);
std::mem::drop(x);
std::mem::forget: Thestd::mem::forgetfunction can be used to manually free memory without calling thedropfunction.
let x = Box::new(5);
std::mem::forget(x);
std::mem::replace: Thestd::mem::replacefunction 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::swapfunction 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
- How to create box str in Rust
- How to replace box value in Rust
- How to deal with box overhead in Rust
- How to check if box is null in Rust
- Using box future in Rust
- Using box from_raw in Rust
- Using box hashmap in Rust
- Example box expression in Rust
- Using enum box in Rust
- How to change box value in Rust
More of Rust
- How to use binary regex in Rust?
- How to perform matrix operations in Rust?
- How to add an entry to a Rust HashMap?
- How to use regex to match a double quote in Rust?
- How to convert struct to JSON string in Rust?
- Yield example in Rust
- How to yield a thread in Rust?
- How to create a HashSet from a Vec in Rust?
- How to convert JSON to a struct in Rust?
- Generator example in Rust
See more codes...