---
title: "Create a function to flatten a nested vector using Rust."  
description: "Create a function to flatten a nested vector using Rust."  
author: "Utpal Vishwas"  
published: 2023-06-20  
updated: 2023-06-23  
canonical: https://www.mindstick.com/forum/158808/create-a-function-to-flatten-a-nested-vector-using-rust  
category: "rust"  
tags: ["rust"]  
reading_time: 2 minutes  

---

# Create a function to flatten a nested vector using Rust.

Create a [function to flatten](https://www.mindstick.com/forum/158771/create-a-function-to-flatten-a-nested-list-in-python) a [nested](https://www.mindstick.com/forum/45/itemcommand-event-in-nested-repeater-and-listview) [vector](https://www.mindstick.com/forum/33499/vector-vs-arraylist-which-has-better-performance-and-why) using Rust.

## Replies

### Reply by Aryan Kumar

Sure, here is a [function](https://www.mindstick.com/articles/13001/multi-statement-table-valued-user-defined-function-in-sql-server) to flatten a nested vector using Rust:

Rust

```plaintext
fn flatten_vector(vector: Vec<Vec<i32>>) -> Vec<i32> {
    let mut flattened_vector: Vec<i32> = Vec::new();
    for inner_vector in vector {
        for element in inner_vector {
            flattened_vector.push(element);
        }
    }
    return flattened_vector;
}

fn main() {
    let nested_vector = vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]];
    let flattened_vector = flatten_vector(nested_vector);
    println!("The flattened vector is: {:?}", flattened_vector);
}
```

This function first defines a function called flatten_vector that takes a Vec of Vec of i32 as input and returns a Vec of i32. The function first initializes a Vec called flattened_vector to an empty vector. Then, the function iterates through the vector vector, adding each element of each inner vector to the flattened_vector vector. Finally, the function returns the flattened_vector vector.

The main function of the program then creates a nested vector called nested_vector with the values 1, 2, 3, 4, 5, 6, 7, 8, 9. The function then calls the flatten_vector function with the nested_vector vector as input. The result of the function call is then printed to the console.

To run the program, you can save it as a file called flatten_vector.rs and then compile it using the following command:

Code snippet

```plaintext
rustc flatten_vector.rs
```

Once the program is compiled, you can run it using the following command:

Code snippet

```plaintext
./flatten_vector
```

This will print the following output to the console:

Code snippet

```plaintext
The flattened vector is: [1, 2, 3, 4, 5, 6, 7, 8, 9]
```


---

Original Source: https://www.mindstick.com/forum/158808/create-a-function-to-flatten-a-nested-vector-using-rust

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
