Como implemento std :: ops comutativos genéricos que envolvem um tipo interno para objetos de características?
Eu tenho:
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}`
eu gostariaH * a
igualara * H
para todosHilbert
s H
. Na linha de outra resposta, tentaria:
impl<T: Hilbert> Mul<T> for f64 {
type Output = T;
fn mul(self, other: T) -> T {
other * self
}
}
Mas isso produz:
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 que isso não é permitido? Qual é a maneira correta de especificar a multiplicação comutativa para um objeto de característica?