Ask Your Question
4

How to add elements from an array into a vector in Rust?

asked 2023-05-04 19:33:16 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-05-04 19:41:01 +0000

qstack gravatar image

You can use the extend method of the Vec type to add elements from an array into a vector in Rust. Here's an example:

let arr = [1, 2, 3];
let mut vec = Vec::new();

vec.extend(&arr);

println!("{:?}", vec); // Output: [1, 2, 3]

In this example, we first create an array arr with the values [1, 2, 3]. We then create an empty vector vec using the Vec::new() function. We then use the extend method to add the elements of the array to the vector.

Note that we pass a reference to the array &arr to the extend method. This is because the extend method accepts an iterable, and arrays in Rust are not directly iterable. However, we can pass a reference to the array, which implements the IntoIterator trait, to the extend method to add its elements to the vector.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-04 19:33:16 +0000

Seen: 7 times

Last updated: May 04 '23