Is it possible to have a trait bound for Add for references?

I'm trying to build a trait with a generic default impl:

use std::ops::*;

pub trait One {
    fn one() -> Self;
}

pub trait Foo<'a> {
    fn foo(&'a self) -> Self;
}

impl<'a, T> Foo<'a> for T where &'a T: Add<&'a T, Output = T>, T: 'a + One {
    fn foo(&'a self) -> T {
        &T::one() + &self
    }
}

As you can see in this playground code 'a is a longer lifetime than useful, the T that gets returned should be able to exist without any of the references passed into add being valid. How can I annotate that correctly?

You can use a higher-rank trait bound (HRTB), where for<'a> &'a T: ...
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=3caf0e31640836611ad26d8db5f56717

4 Likes