I'm just getting started with Rust and have hit upon an issue where I'm getting a bit lost in types, pointers, borrowing and ownership.
I have a vector of Person
structs, each of which has a name
property. I'd like to collect all the names into another vector, and then check if that list contains a given string.
This is my code:
struct Person {
name: String,
}
fn main() {
let people = vec![Person {
name: String::from("jack"),
}];
let names: Vec<_> = people.iter().map(|p| p.name).collect();
let some_name = String::from("bob");
if names.iter().any(|n| n == some_name) {
}
}
This fails to compile:
error[E0277]: can't compare `&String` with `String`
--> src/main.rs:13:31
|
13 | if names.iter().any(|n| n == some_name) {
| ^^ no implementation for `&String == String`
|
= help: the trait `PartialEq<String>` is not implemented for `&String`
I think names should have the type Vec<String>
, so I'm a bit lost as to where the &String
comes from. Is this a case of me holding it wrong? I'm most familiar with JavaScript so I'm trying to apply those patterns, and may be not doing it in the most "rusty" way!