如何创建一个仅限于实现另一个特征的类型的特征,其中 `&Self` self 是特征的类型?
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
将仅在该总和期间使用?
您可以使用 higher-ranked trait bound 使约束在整个生命周期内通用,这样它就不会被限制为使用特征上定义的约束:
pub trait MyTrait: for<'a> std::ops::AddAssign<&'a Self> {}
// ^^^^^^^
例如,我希望每个 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
将仅在该总和期间使用?
您可以使用 higher-ranked trait bound 使约束在整个生命周期内通用,这样它就不会被限制为使用特征上定义的约束:
pub trait MyTrait: for<'a> std::ops::AddAssign<&'a Self> {}
// ^^^^^^^