Если это действительно то же самое, вы можете предоставить реализацию по умолчанию в черте.
я есть:
use std::ops::{Add, Div, Mul, Neg, Sub};
pub trait Hilbert:
Add + Sub + Mul + Div + Neg + Mul<f64, Output = Self> + Div<f64, Output = Self> + Sized + Copy
{
fn dot(&self, other: &Self) -> f64;
fn magnitude(&self) -> f64;
}
fn g<T: Hilbert>(x: T) -> f64 {
let a = (x * 2.0).dot(&x);
let b = (2.0 * x).dot(&x);
a + b
}
error[E0277]: cannot multiply `T` to `{float}`
--> src/main.rs:12:18
|
12 | let b = (2.0 * x).dot(&x);
| ^ no implementation for `{float} * T`
|
= help: the trait `std::ops::Mul<T>` is not implemented for `{float}`
Я хотел быH * a
в равнойa * H
для всехHilbert
s H
, В духе другого ответа я бы попробовал:
impl<T: Hilbert> Mul<T> for f64 {
type Output = T;
fn mul(self, other: T) -> T {
other * self
}
}
Но это дает:
error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct<T>`); only traits defined in the current crate can be implemented for a type parameter
--> src/main.rs:16:1
|
16 | / impl<T: Hilbert> Mul<T> for f64 {
17 | | type Output = T;
18 | |
19 | | fn mul(self, other: T) -> T {
20 | | other * self
21 | | }
22 | | }
| |_^
Почему это запрещено? Как правильно указать коммутативное умножение для объекта черты?