[英]How do I make a trait that is restricted to types who implement another trait where `&Self` self is a trait's type?
例如,我希望每个MyTrait
都实现AddAssign<&'a Self>
。 据我所知,在将'a
放置在编译器想要的位置之后:
trait MyTrait<'a>: 'a + std::ops::AddAssign<&'a Self> {}
fn func<'a, T: MyTrait<'a>>(a: &mut T, b: T) {
*a += &b;
}
此代码失败并出现以下错误:
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`.
我如何告诉编译器 &b 只会在该总和期间使用?
您可以使用更高级别的特征绑定来使约束在整个生命周期中通用,因此它不限于使用特征上定义的约束:
pub trait MyTrait: for<'a> std::ops::AddAssign<&'a Self> {}
// ^^^^^^^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.