此问题已在此处有答案:
How to write a trait bound for adding two references of a generic type?(1个答案)
15小时前关门了。
下面是我的原始代码,它可以工作:
pub trait Arith {
fn square(x: &Self) -> Self;
}
impl Arith for i32 {
fn square(x: &i32) -> i32 {
x * x
}
}
impl Arith for f32 {
fn square(x: &f32) -> f32 {
x * x
}
}
我想用一种通用的方式来做:
pub trait Arith where Self: Sized + Mul<&Self, Output = Self> {
fn square(x: &Self) -> Self {
x * x
}
}
似乎我遇到了一些生命周期注解问题:
error[E0637]: `&` without an explicit lifetime name cannot be used here
--> src/main.rs:7:41
|
7 | pub trait Arith where Self: Sized + Mul<&Self, Output = Self> {
| ^ explicit lifetime name needed here
|
help: consider introducing a higher-ranked lifetime here with `for<'a>`
--> src/main.rs:7:37
|
7 | pub trait Arith where Self: Sized + Mul<&Self, Output = Self> {
| ^
error[E0311]: the parameter type `Self` may not live long enough
--> src/main.rs:7:37
|
7 | pub trait Arith where Self: Sized + Mul<&Self, Output = Self> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^ ...so that the reference type `&Self` does not outlive the data it points at
Some errors have detailed explanations: E0311, E0637.
For more information about an error, try `rustc --explain E0311`.
我尝试了编译器建议的几种方法,但无法使其工作。我更喜欢函数调用看起来像Arith::square(&x)
。
1条答案
按热度按时间s3fp2yjn1#
根据@JaredSmith的建议。以下代码适用于我: