Home Â» rust Â» Rust: Check if vectors are equal

# Rust: Check if vectors are equal

## Introduction

In this tutorial, we will learn how to check if two vectors are equal in Rust. We will cover three different methods of comparing vectors: using the `==` operator, using the `.eq()` method, and using the `.iter().eq()` method. Each method provides a way to determine if two vectors contain the same elements in the same order. We will provide code examples for each method along with the output, so that you can understand how to use them in your own programs.

## Check if vectors are equal in Rust Examples

### Using the `==` Operator

The `==` operator can be used to compare two vectors for equality. The operator will return `true` if the vectors contain the same elements in the same order, and `false` otherwise.

```fn main() {
let vec1 = vec![1, 2, 3];
let vec2 = vec![1, 2, 3];
let vec3 = vec![3, 2, 1];

// Using the `==` operator
println!("vec1 == vec2 : {}", vec1 == vec2);
println!("vec1 == vec3 : {}", vec1 == vec3);
}```

The output of the program will be:

```vec1 == vec2 : true
vec1 == vec3 : false```

### Using the `.eq()` Method

The `.eq()` method can also be used to compare two vectors for equality. The method takes another vector as a parameter and returns `true` if the vectors contain the same elements in the same order, and `false` otherwise.

```fn main() {
let vec1 = vec![1, 2, 3];
let vec2 = vec![1, 2, 3];
let vec3 = vec![3, 2, 1];

// Using the `.eq()` method
println!("vec1.eq(&vec2) : {}", vec1.eq(&vec2));
println!("vec1.eq(&vec3) : {}", vec1.eq(&vec3));
}```

The output of the program will be:

```vec1.eq(&vec2) : true
vec1.eq(&vec3) : false```

### Using the `.iter().eq()` Method

The `.iter().eq()` method can also be used to compare two vectors for equality. The method takes another vector as a parameter and returns `true` if the vectors contain the same elements in the same order, and `false` otherwise.

```fn main() {
let vec1 = vec![1, 2, 3];
let vec2 = vec![1, 2, 3];
let vec3 = vec![3, 2, 1];

// Using the `.iter().eq()` method
println!("vec1.iter().eq(vec2.iter()) : {}", vec1.iter().eq(vec2.iter()));
println!("vec1.iter().eq(vec3.iter()) : {}", vec1.iter().eq(vec3.iter()));
}```

The output of the program will be:

```vec1.iter().eq(vec2.iter()) : true
vec1.iter().eq(vec3.iter()) : false```

## Conclusion

In this tutorial, we learned how to check if two vectors are equal in Rust using the `==` operator, the `.eq()` method, and the `.iter().eq()` method. Each method provides a way to compare vectors for equality and determine if they contain the same elements in the same order.