I have a zero-copy implementation of an operation:
impl<'a, 'b> Add<&'b Key> for &'a Key {
type Output = Key;
fn add(self, rhs: &'b Key) -> Key {
// ... calculate sum from given references ...
Key::new(sum)
}
}
I have several structs with similar properties that all implement Add with two references as input, returning a new value, i.e. &'a T: Add<&'b T, Output = T>
I'd like to write a generic function that can make use of any of these implementations, but nothing seems to satisfy the borrow checker:
pub struct FixedSet<T> {
items: Vec<Option<T>>,
}
impl<T: Clone + PartialEq> FixedSet<T> {
...
pub fn sum<'a>(&self) -> Option<T>
where
T: 'a,
&'a T: Add<&'a T, Output=T>,
{
if self.items.len() == 0 {
return None
}
let mut iter = self.items.iter(); //** Error **
let mut sum = iter.next().unwrap().as_ref().unwrap().clone();
for v in iter {
let t = v.as_ref().unwrap();
sum = &sum + t; // *A*
}
Some(sum)
}
The error is: error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements.
I'd like to tell the compiler, "Hey, when calling add with two references to T, don't worry, the references only need to live until the return from add at A"; but I can't seem to get it right.