Vector Element Assignment

Hi,

I have started learning Rust and I have a question regarding assigning elements in vectors. For example, if I have two vectors:

let x: Vec<f64> = vec![1.0, 2.0, 3.0, 4.0, 5.0];
let y: Vec<f64> = vec![6.0, 7.0, 8.0, 9.0, 10.0];

And I do the following:

x[0] = y[4];

Does this create a reference to the element or does it copy the element from y?

Thank you.

It will copy the value.

In general, Rust's single ownership principle makes it very difficult to accidentally put a reference to the same thing several places when you meant to create separate copies.

2 Likes

It technically moves the element from y to x. In this case since f64 implements the Copy trait, it copies it. But if you had a vector of strings, then Rust wouldn't allow you to do this.

let mut x = vec![String::from("hello"), String::from("world")];
let y = vec![String::from("foo"), String::from("bar")];
x[0] = y[0]; // Gives you an error

Playground link
Also, x needs to be declared mut.

3 Likes

Thank you for the explaination. I realized I did not declare x as mut, my mistake. As a follow up question, if I have a vec of structs, would it then also copy the struct?

Yes, if it implemented the Copy trait. Rust generally treats types uniformly. It matters much more what traits a type implements; whether it's a struct or an enum or a primitive built-in is usually not very important.

2 Likes

Thank you all for the help. Have a nice day!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.