The following rust code creates a struct "Foo" that models a person with a name and age. Two mutator methods exist: "set_name" and "set_age". The "set_name" uses "self as a reference" and "set_age" "self as a value".
The ultimate goal here is to understand how these two approaches for methods can be used against a Foo element stored in a vector.
The question boils down to the end of the code where, in comments, I have a failed attempt where I am trying to make "Jane Doe" 19 years old now that she has been moved into a vector (and college!) owned by "bar2". The code above that was able to make her 18 when she was in a the variable "bar1" using shadowing.
When the statement which fails is uncommented the compiler emits the following error:
error[E0507]: cannot move out of index of `Vec<Foo>`
--> src/main.rs:36:15
|
36 | bar2[0] = bar2[0].set_age(19); // Nope, try again!
| ^^^^^^^ move occurs because value has type `Foo`, which does not implement the `Copy` trait
error: aborting due to previous error
Thank you all very much for your thoughts and insight.
struct Foo {
name: String,
age: u32,
}
impl Foo {
fn display(self: &Foo) {
println!("age={}, name={}", self.age, self.name);
}
fn set_name(&mut self, name: &str) {
self.name = name.to_string();
}
fn set_age(mut self, age: u32) -> Foo {
self.age = age;
Foo{ name: self.name, age: self.age }
}
}
fn main() {
let mut foo = Foo{ age: 0, name: "Nobody".to_string() };
foo.display();
foo.set_name("Jane Doe in High School");
let foo = foo.set_age(17);
foo.display();
let mut bar1 = foo;
bar1.set_name("Jane Doe Can Vote");
let bar1 = bar1.set_age(18); // This works!
bar1.display();
let mut bar2: Vec<Foo> = Vec::new();
bar2.push(bar1);
bar2[0].set_name("Jane Doe In College");
// Now make Jane Doe a year older.
// bar2[0] = bar2[0].set_age(19); // Nope, try again!
bar2[0].display();
}
Running this code in the current form produces the following output:
$ cargo run
...<banner stuff>...
age=0, name=Nobody
age=17, name=Jane Doe in High School
age=18, name=Jane Doe Can Vote
age=18, name=Jane Doe In College
So the goal is to replace my failed comment code so that the last line reads:
age=19, name=Jane Doe In College