Home
Rust
swap Function Examples
This page was last reviewed on May 11, 2023.
Dot Net Perls
Swap. Sometimes in Rust programs we have two variables that we want to exchange values between. The first should have the second's value, and the opposite.
With mem swap, part of the standard library in Rust, we can do this in an elegant way. And for values within a vector, we can use the swap() method for a similar result.
This program uses two separate functions: it uses the mem swap() function, and it also uses the swap() method on a vector. The first 2 parts use mem swap.
Part 1 We have 2 integers on the stack, a left and right value. When we invoke swap, they exchange values.
Part 2 Here we call mem swap() on 2 vectors on the stack. Swap() works well for even heap-allocated types like Vector.
vec
Part 3 We use a separate swap() method to exchange 2 values within a vector. We exchange the first with the second.
use std::mem; fn main() { // Part 1: use mem swap on 2 local integers. let mut left = 10; let mut right = 20; println!("{left} {right}"); mem::swap(&mut left, &mut right); println!("{left} {right}"); // Part 2: use mem swap on 2 vector variables. let mut left = vec![10, 11]; let mut right = vec![20, 21]; println!("{:?} {:?}", left, right); mem::swap(&mut left, &mut right); println!("{:?} {:?}", left, right); // Part 3: use swap() method on vector to swap 2 elements. let mut values = vec![100, 200, 300, 400]; println!("{:?}", values); values.swap(0, 1); println!("{:?}", values); }
10 20 20 10 [10, 11] [20, 21] [20, 21] [10, 11] [100, 200, 300, 400] [200, 100, 300, 400]
Clippy warning. In Rust we should be using the "cargo clippy" tool to ensure our programs are free of certain issues. The swap() function is recommended by clippy in certain situations.
For program quality and readability, the mem swap() function is usually worth using. It helps reduce code and assignments in a function.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 11, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.