Rust, Software Development

Swap Between Vec Elements in Rust

Rust Lang
Photo by Mark Vegera from Pexels

Swapping between Vec elements in Rust can be a little tricky. The get method returns Option<&T>, and the lone swap method accepts an index and a value – not a reference. There is an alternative, though. But it uses unsafe codes.

Swap Between Vec Elements

When we swap between Vec elements, it means any two items replace each other’s value. We can do it safely or unsafely.

Safe Swap

A safe swap between Vec elements in Rust means we are not using the unsafe keyword. Consider the following codes. They clone any two items and replace each other’s value using the swap method.

The codes generate the following output.

Unsafe Swap

The next implementation requires creating a trait and implementing it for a specific type of Vec. Let’s say we have a struct Person and an instance of Vec<Person>.

We want, for instance, to swap between the first and third elements from


we need to extend Vec.

First, we need to create a trait with one method that accepts the indexes of elements to swap.

Then, we need to implement the trait for Vec<Person>.

Lastly, we can swap between Vec elements in Rust in the following way.

The codes generate the following output.

You Might Also Like