Rust Lang

Convert a Rust Vector into an Array

What Is a Rust Vector?

A Rust vector, also known as a “vec”, refers to a dynamic array that can grow or shrink as needed. It is a standard library type and is one of Rust’s most commonly used data structures.

Internally, a vec is represented by a heap-allocated buffer that holds a sequence of elements of the same type. The allocated buffer can dynamically expand as we add more elements to the vector.

Once the buffer becomes full, Rust allocates a new large buffer and copies the elements of the old buffer into the new one. This process is known as “reallocation” and can become quite expensive if the vector contains many elements.

Hence, Rust typically over-allocates the buffer to avoid excessive reallocations to provide some extra space for future growth.

To create a new vector in Rust, we can use the vec! macro as shown in the following:

let my_vec = vec![1, 2, 3, 4, 5];

This creates a new vector with five integer elements. To add the elements to a vector, we can use the “push” method:

let mut my_vec = vec![1, 2, 3];
my_vec.push(4);

Note: We must ensure that the vector is mutable before we attempt to modify it.

What Is a Rust Array?

Let’s talk about an array in Rust. In Rust, an array refers to a fixed-size collection of elements of the same type. Unlike vector, an array has a fixed length which is determined at compile time and which cannot be changed at runtime. In addition, arrays are stack-allocated which means that the array’s memory is allocated on the stack when the array is declared.

Some common/key properties of arrays in Rust include the following:

  • Fixed Size – The length of an array is determined at compile time. Therefore, you cannot modify its size once the array is created.
  • Stack Allocation – The memory for an array is allocated on the stack which makes the arrays fast and efficient to work with.
  • Indexing – We can access the elements in an array using indexing or index notation. Similar to a vector, arrays in Rust are 0-based indexes where the first element has an index 0f 0.
  • Type Safety – Like all Rust types, arrays are type-safe which means that the compiler checks if the types of the elements in an array match the declared type of the array itself. This helps prevent type errors at runtime and makes it easier to write the correct Rust code.

In Rust, we can define an array using the square bracket notation as shown in the following:

let my_array = [1, 2, 3, 4, 5];

In the previous example, we create a new array with five integer elements. It is good to remember that the number of elements in the array determines the array length.

Since the arrays in Rust have fixed length, they are helpful in situations where the size of a collection is known in advance and does not need to change at runtime.

Convert a Rust Vector Into an Array

In some cases, you may come across an instance where you need to convert a Rust vector into an array.

To convert a Rust vector to an array, we can use the into_boxed_slice() method to convert the vector into a boxed slice. Then, we use the Box::into_array() method to convert the boxed slice into an array.

Rust Into_Boxed_Slice Method

The into_boxed_method_slice method is part of Rust’s standard library which is defined in the vec type. This method allows us to convert a Rust vec! macro

tor into a boxed slice. Specifically, the method returns a Box<[T]> type where the T represents the element type in the vector.

If you are unfamiliar with it, a boxed slice in Rust refers to a dynamically-allocated slice of elements where the memory is stored in a heap rather than a stack.

Rust Box:Into_Array Method

As the name suggests, this method converts a boxed slice into an array. This process allows us to convert a Rust vector into a boxed slice and an array.

An example is as follows:

fn main() {
    let v = vec![1, 2, 3, 4, 5];
    let boxed_slice: Box<[i32]> = v.into_boxed_slice();
    let arr: [i32; 5] = boxed_slice.into();
    println!("Type of v: {:?}", std::any::type_name::<Vec<i32>>());
    println!("Type of boxed_slice: {:?}", std::any::type_name::<Box<[i32]>>>());
    println!("Type of arr: {:?}", std::any::type_name::<[i32; 5]>>());
    println!("{:?}", arr);
}

NOTE: The conversion traits may be missing depending on your rust version. Kindly confront the documentation for your Rust version to learn more.

Another way that you can use to convert a vector to an array is using the TryInto trait as shown in the following example:

use std::convert::TryInto;

fn main() {
    let v = vec![1, 2, 3, 4, 5];
    let my_array: Result<[i32; 5], _> = v.try_into();
    match my_array {
        Ok(arr) => println!("{:?}", arr),
        Err(_) => println!("Failed to convert vector to array."),
    }
}

This should allow you to convert an input vector to an array.

Conclusion

This tutorial explored about the Rust vector types, arrays, boxed slices, and more. We also discovered two main methods of converting an input vector to an array.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list