To check if two arrays are equal in Rust, you can use the ==
operator for arrays with the same elements and manually compare elements for arrays with different elements.
In this example,
arr1
and arr2
with the same elements.==
operator to check if the arrays are equal and store the result in the variable equal1
.==
operator checks if two arrays have the same elements in the same order.equal1
to the console.fn main() {
let arr1 = [1, 2, 3];
let arr2 = [1, 2, 3];
let equal1 = arr1 == arr2;
println!("Arrays are equal: {:?}", equal1);
}
Arrays are equal: true
In this example,
arr3
and arr4
with different elements.equal2
.equal2
is set to true
; otherwise, it's set to false
.equal2
to the console.fn main() {
let arr3 = [1, 2, 3];
let arr4 = [3, 2, 1];
let mut equal2 = true;
for (a, b) in arr3.iter().zip(arr4.iter()) {
if a != b {
equal2 = false;
break;
}
}
println!("Arrays are equal: {:?}", equal2);
}
Arrays are equal: false
In this tutorial, we learned How to check if Two Arrays are Equal in Rust language with well detailed examples.