I'm using a lot the newtype pattern to add type semantics to my code.
But I have been stucked with the following issue:
#[derive(PartialEq, Eq)]
pub struct ItemName(String);
impl From<&str> for ItemName {
fn from(str: &str) -> Self {
ItemName(str.to_string())
}
}
fn main() {
let vec: Vec<ItemName> = Vec::new();
vec.push("Apple");
assert!(vec.contains("Apple"));
}
Which raise the error:
error[E0308]: mismatched types
--> src/main.rs:12:14
|
12 | vec.push("Apple");
| ^^^^^^^ expected struct `ItemName`, found `&str`
error[E0308]: mismatched types
--> src/main.rs:13:26
|
13 | assert!(vec.contains("Apple"));
| ^^^^^^^ expected struct `ItemName`, found `str`
|
= note: expected reference `&ItemName`
found reference `&'static str`
Rust playground : Rust Playground
For some reason the compiler doesn't understand that the vec only contains ItemName and so that he can use the Form<&str> implementation to convert the &str to ItemName. How can I solve this issue?