gpt4 book ai didi

rust - 有没有办法在另一个特征之上实现一个特征?

转载 作者:行者123 更新时间:2023-11-29 07:46:40 26 4
gpt4 key购买 nike

<分区>

我正在尝试创建一个基本特征,它将实现其他运算符特征(AddSubtractMultiplyDivide 等...)对我来说。

编译失败,它看起来像一个带有 Sized 的问题,但即使当 Measurement 设置为需要 Sized 它也不起作用.这可能吗?

use std::ops::Add;

#[derive(Copy, Clone, Debug)]
struct Unit {
value: f64,
}

impl Unit {
fn new(value: f64) -> Unit {
Unit { value: value }
}
}

trait Measurement: Sized {
fn get_value(&self) -> f64;
fn from_value(value: f64) -> Self;
}

impl Measurement for Unit {
fn get_value(&self) -> f64 {
self.value
}
fn from_value(value: f64) -> Self {
Unit::new(value)
}
}

// This explicit implementation works
/*
impl Add for Unit {
type Output = Unit;

fn add(self, rhs: Unit) -> Unit {
let a = self.get_value();
let b = rhs.get_value();
Unit::from_value(a + b)
}
}
*/

// This trait implementation does not
impl Add for Measurement {
type Output = Self;

fn add(self, rhs: Self) -> Self {
let a = self.get_value();
let b = rhs.get_value();
Self::from_value(a + b)
}
}

fn main() {
let a = Unit::new(1.5);
let b = Unit::new(2.0);
let c = a + b;

println!("{}", c.get_value());
}

( playground )

error[E0277]: the trait bound `Measurement + 'static: std::marker::Sized` is not satisfied
--> src/main.rs:42:6
|
42 | impl Add for Measurement {
| ^^^ `Measurement + 'static` does not have a constant size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `Measurement + 'static`

error[E0038]: the trait `Measurement` cannot be made into an object
--> src/main.rs:42:6
|
42 | impl Add for Measurement {
| ^^^ the trait `Measurement` cannot be made into an object
|
= note: the trait cannot require that `Self : Sized`

error[E0038]: the trait `Measurement` cannot be made into an object
--> src/main.rs:43:5
|
43 | type Output = Self;
| ^^^^^^^^^^^^^^^^^^^ the trait `Measurement` cannot be made into an object
|
= note: the trait cannot require that `Self : Sized`

error[E0038]: the trait `Measurement` cannot be made into an object
--> src/main.rs:45:5
|
45 | fn add(self, rhs: Self) -> Self {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Measurement` cannot be made into an object
|
= note: the trait cannot require that `Self : Sized`

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com