简体   繁体   中英

How do I make a trait that is restricted to types who implement another trait where `&Self` self is a trait's type?

For instance, I want every MyTrait to implement AddAssign<&'a Self> . This is as far as I got, after placing 'a where the compiler wanted:

trait MyTrait<'a>: 'a + std::ops::AddAssign<&'a Self> {}

fn func<'a, T: MyTrait<'a>>(a: &mut T, b: T) {
    *a += &b;
}

This code fails with the following error:

error[E0597]: `b` does not live long enough
 --> src/main.rs:4:11
  |
3 | fn func<'a, T: MyTrait<'a>>(a: &mut T, b: T) {
  |         -- lifetime `'a` defined here
4 |     *a += &b;
  |           ^^
  |           |
  |           borrowed value does not live long enough
  |           requires that `b` is borrowed for `'a`
5 | }
  | - `b` dropped here while still borrowed

For more information about this error, try `rustc --explain E0597`.

How do I tell the compiler that &b will only be used for the duration of that sum?

You can use a higher-ranked trait bound to make the constraint generic over the lifetime so it isn't constrained to using the one defined on the trait:

pub trait MyTrait: for<'a> std::ops::AddAssign<&'a Self> {}
                // ^^^^^^^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM