I am trying to implement PartialEq between the structure I created and other types for which my structure implements the From property. The actual code is more complex and implements From for other types, but this is a stripped-down version of the main problem.
I want to be able to do:
let s = Data::from(5); assert_eq!(5, s);
This is the base code:
struct Data { data: i64, } impl From<i64> for Data { fn from(v: i64) -> Data { Data { data: v } } } impl<'a> From<&'a i64> for Data { fn from(v: &'a i64) -> Data { Data { data: v.clone() } } }
This was my first attempt:
impl<T> PartialEq<T> for Data where T: Into<Data> { fn eq(&self, other: &T) -> bool { let o = Data::from(other); self.data == o.data } }
but I get an error:
error: the trait bound `Data: std::convert::From<&T>` is not satisfied [--explain E0277] --> <anon>:21:17 |> 21 |> let o = Data::from(other); |> ^^^^^^^^^^ help: consider adding a `where Data: std::convert::From<&T>` bound note: required by `std::convert::From::from`
So, I changed the trait associated with what the compiler suggested, and added all the requested lifetimes to fix the missing lifetime specifier error:
impl<'a, T> PartialEq<T> for Data where T: 'a, Data: From<&'a T> { fn eq(&self, other: &'a T) -> bool { let o = Data::from(other); self.data == o.data } }
From which i get
error: method not compatible with trait [--explain E0308] --> <anon>:31:5 |> 31 |> fn eq(&self, other: &'a T) -> bool { |> ^ lifetime mismatch note: expected type `fn(&Data, &T) -> bool` note: found type `fn(&Data, &'a T) -> bool` note: the anonymous lifetime
And now I'm lost, as he offers to do what I did, and he refused ...: /
Playground Code