rust 通用性状功能实现[重复]

sigwle7e  于 2023-05-22  发布在  其他
关注(0)|答案(1)|浏览(141)

此问题已在此处有答案

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)

s3fp2yjn

s3fp2yjn1#

根据@JaredSmith的建议。以下代码适用于我:

pub trait Arith
{
    fn square(x: &Self) -> Self
    where
        Self: Sized,
        for<'a> &'a Self: Sized+Mul<&'a Self, Output=Self>,
    {
        x * x
    }
}

impl Arith for i32 { }
impl Arith for f32 { }

相关问题