Code Logo

Create Vector with vec![]

Published at25 Jul 2026
Rust Data Structures Easy 0 views
Like0

Write a Rust function that takes three integer values and returns a vector containing them using the vec![] macro. The vec![] macro is Rust's idiomatic way to create vectors, providing a concise syntax similar to array literals in other languages.

The vec![] macro expands to code that creates a Vec and pushes each element into it. It is more convenient than manually creating an empty Vec and calling push() for each element. The macro works with any number of elements and automatically infers the element type from the provided values.

Vectors (Vec) are Rust's growable array type. They store elements on the heap and can grow or shrink dynamically. The vec![] macro handles memory allocation automatically, making it the recommended way to create vectors with initial elements.

Time complexity is O(n) where n is the number of elements. The macro internally allocates the vector and pushes each element. Space complexity is O(n) for the resulting vector allocation.

Edge cases include all elements being the same value, negative numbers, and ensuring the function works with the i32 type.

Example Input & Output

Example 1
Input
7,7,7
Output
[7,7,7]
Explanation

All sevens

Example 2
Input
-1,0,1
Output
[-1,0,1]
Explanation

With negative and zero

Example 3
Input
1,2,3
Output
[1,2,3]
Explanation

Three elements

Example 4
Input
42,42,42
Output
[42,42,42]
Explanation

All same value

Example 5
Input
10,20,30
Output
[10,20,30]
Explanation

Three increasing

Algorithm Flow

Recommendation Algorithm Flow for Create Vector with vec![]
Recommendation Algorithm Flow for Create Vector with vec![]

Solution Approach

fn solution(a: i32, b: i32, c: i32) -> Vec<i32> {
    vec![a, b, c]
}

Best Answers

rust - Approach 1
fn solution(a: i32, b: i32, c: i32) -> Vec<i32> {
    vec![a, b, c]
}