I have a struct like below.
struct Test {
field: Vec<String>,
}
I am passing a reference to this struct as a function argument.
I have a second function that takes a &Vec<String>
.
fn main() {
let obj = Test { field: vec![] };
takes_ref_to_struct(&obj);
}
fn takes_ref_to_struct(obj: &Test) {
takes_ref_to_field(obj.field);
}
fn takes_ref_to_field(field: &Vec<String>) {}
This usage will not compile due to the error below:
error[E0308]: mismatched types
--> src/main.rs:11:24
|
11 | takes_ref_to_field(obj.field);
| ------------------ ^^^^^^^^^ expected `&Vec<String>`, found `Vec<String>`
| |
| arguments to this function are incorrect
|
= note: expected reference `&Vec<String>`
found struct `Vec<String>`
note: function defined here
--> src/main.rs:14:4
|
14 | fn takes_ref_to_field(field: &Vec<String>) {}
| ^^^^^^^^^^^^^^^^^^ -------------------
help: consider borrowing here
|
11 | takes_ref_to_field(&obj.field);
Obviously I can just add the suggested borrow, but why is this necessary? If I try to mutate the field
fn takes_ref_to_struct(obj: &Test) {
obj.field.clear();
}
the compiler complains as expected
error[E0596]: cannot borrow `obj.field` as mutable, as it is behind a `&` reference
--> src/main.rs:11:5
|
11 | obj.field.clear();
| ^^^^^^^^^^^^^^^^^ `obj` is a `&` reference, so the data it refers to cannot be borrowed as mutable