在学习Rust的过程中,我试图为向量的每个元素添加一个整数:
trait Arith: Copy {
fn add(self, b: Self) -> Self;
fn mult(self, b: Self) -> Self;
fn print(self);
}
impl Arith for i32 {
fn add(self, b: Self) -> Self {
self + b
}
fn mult(self, b: Self) -> Self {
self * b
}
fn print(self) {
println!("Val = {}", self);
}
}
fn vec_add<T: Arith>(vec: &mut Vec<T>) {
for e in vec.iter_mut(){
/* e is of type &mut i32. But you can give it to print() which
expects i32 because rust derefs it implicitly */
e.print();
e.add(5);
}
}
fn main() {
println!("Hello World");
let mut vec: Vec<i32> = vec![1,2,3,4,5];
vec_add(&mut vec);
}
但我面临以下问题:
<anon>:33:15: 33:16 error: mismatched types:
expected `T`,
found `_`
(expected type parameter,
found integral variable) [E0308]
<anon>:33 e.add(5);
你能解释一下我在这里犯的错误吗?
答案 0 :(得分:4)
数字5是一个整数(我认为它默认为i32
或者u32
,目前我不记得了)。类型T
,它是泛型类型,可以是任何东西,因此通常5不是T
的相同类型。您可以强制T
为整数,也可以这样更改vec_add
:
fn vec_add<T: Arith>(vec: &mut Vec<T>, val: T){
for e in vec.iter_mut(){
/* e is of type &mut i32. But you can give it to print() which
expects i32 because rust derefs it implicitly */
e.print();
e.add(val);
}
}
fn main(){
println!("Hello World");
let mut vec: Vec<i32> = vec![1,2,3,4,5];
vec_add(&mut vec, 5);
}