我在Rust中编写LoG过滤器,我想使用|
作为元素范围乘法运算符(a_{i,j} * b_{i,j}
)的运算符,但是编译器抱怨Output
结果。它说self[(i, j)] * out[(i, j)]
不等于Mul<N>::Output
。
impl<N> BitOr<Matrix<N>> for Matrix<N> where N: Mul<N> {
type Output = Matrix<N>;
fn bitor(self, other: Matrix<N>) -> Matrix<N> {
if self.width() != other.width() ||
self.height() != other.height() {
panic!("Matrices need to have equal dimensions");
}
let mut out = Matrix::new(self.width(), self.height());
for i in 0..(self.width()) {
for j in 0..(self.height()) {
out[(i, j)] = self[(i, j)] * out[(i, j)];
}
}
out
}
}
有没有办法根据Mul<N>::Output
类型设置输出?
答案 0 :(得分:3)
我想这应该有效:
impl<N> BitOr<Matrix<N>> for Matrix<N> where N: Mul<N> {
type Output = Matrix<<N as Mul<N>>::Output>;
fn bitor(self, other: Matrix<N>) -> Matrix<<N as Mul<N>>::Output> {
if self.width() != other.width() ||
self.height() != other.height() {
panic!("Matrices need to have equal dimensions");
}
let mut out = Matrix::new(self.width(), self.height());
for i in 0..(self.width()) {
for j in 0..(self.height()) {
out[(i, j)] = self[(i, j)] * out[(i, j)];
}
}
out
}
}
答案 1 :(得分:1)
你没有提供一个小的可运行的例子,所以我自己做了。这有效:
use std::ops::{Mul,BitOr};
#[derive(Copy,Show)]
struct Matrix<N>(N, N);
impl<N> BitOr<Matrix<N>> for Matrix<N> where N: Mul<N, Output=N> {
type Output = Matrix<N>;
fn bitor(self, other: Matrix<N>) -> Matrix<N> {
Matrix(self.0 * other.0, self.1 * other.1)
}
}
fn main() {
let a = Matrix(-1,-1);
let b = Matrix(2,3);
let c = a | b;
println!("{:?}", c)
}
我必须做的主要事情是N: Mul<N, Output=N>
,它指定N
必须可以与另一个N
相乘,而会导致另一个{{1} }}