我正在尝试在Rust中实现泛型函数,其中对参数的唯一要求是应该定义乘法运算.我正在尝试实现一个通用的"权力",但将使用更简单的cube
功能来说明问题:
use std::ops::Mul;
fn cube<T: Mul>(x: T) -> T {
x * x * x
}
fn main() {
println!("5^3 = {}", cube(5));
}
Run Code Online (Sandbox Code Playgroud)
编译时我收到此错误:
error[E0369]: binary operation `*` cannot be applied to type `<T as std::ops::Mul>::Output`
--> src/main.rs:4:5
|
4 | x * x * x
| ^^^^^^^^^
|
= note: an implementation of `std::ops::Mul` might be missing for `<T as std::ops::Mul>::Output`
Run Code Online (Sandbox Code Playgroud)
这是什么意思?我选择了错误的特质吗?我该如何解决这个问题?
我有一个Fibonacci
可以用作任何一个迭代器实现结构One
,Zero
,Add
和Clone
.这适用于所有整数类型.
我想将这个结构用于BigInteger
使用a实现Vec
并且调用昂贵的类型clone()
.我想Add
在两个引用上T
使用然后返回一个新的T
(然后没有克隆).
对于我的生活,我不能制作一个虽然编译的...
工作:
extern crate num;
use std::ops::Add;
use std::mem;
use num::traits::{One, Zero};
pub struct Fibonacci<T> {
curr: T,
next: T,
}
pub fn new<T: One + Zero>() -> Fibonacci<T> {
Fibonacci {
curr: T::zero(),
next: T::one(),
}
}
impl<'a, T: Clone + Add<T, Output = T>> Iterator for Fibonacci<T> {
type Item = T;
fn next(&mut …
Run Code Online (Sandbox Code Playgroud)