¿Cómo implemento std :: ops conmutativos genéricos que involucran un tipo incorporado para objetos de rasgos?
Yo tengo:
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}`
Me gustaríaH * a
A iguala * H
para todosHilbert
s H
. En la línea de otra respuesta, intentaría:
impl<T: Hilbert> Mul<T> for f64 {
type Output = T;
fn mul(self, other: T) -> T {
other * self
}
}
Pero esto produce:
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 | | }
| |_^
¿Por qué esto no está permitido? ¿Cuál es la forma correcta de especificar la multiplicación conmutativa para un objeto de rasgo?