Home
Rust
swap Function Examples
Updated 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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on May 11, 2023 (new).
Home
Changes
© 2007-2025 Sam Allen