rustHow to swap elements in a Rust slice?
Swapping elements in a Rust slice can be done using the swap
method. This method takes two indices as arguments and swaps the elements at those indices.
Example
let mut v = [1, 2, 3, 4];
v.swap(0, 3);
Output example
[4, 2, 3, 1]
Code explanation
let mut v = [1, 2, 3, 4];
: Declares a mutable slicev
with elements1
,2
,3
, and4
.v.swap(0, 3);
: Calls theswap
method onv
with arguments0
and3
, which swaps the elements at indices0
and3
.
Helpful links
Related
- How to calculate the sum of a Rust slice?
- How to get the last element of a Rust slice?
- How to iterate over a Rust slice with an index?
- How to convert a Rust slice to a fixed array?
- How to get the first element of a slice in Rust?
- How to check if a Rust slice contains a certain value?
- How to split a Rust slice?
- How to map a Rust slice?
- How to concatenate Rust slices?
More of Rust
- How to implement PartialEq for a Rust HashMap?
- How to use regex to match a double quote in Rust?
- How to create a Rust HashMap from a vector of tuples?
- How to calculate the sum of a Rust slice?
- How to match a URL with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to replace strings using Rust regex?
- How to parse a file with Rust regex?
- How to ignore case in Rust regex?
- How to match the end of a line in a Rust regex?
See more codes...