如何在类型之间进行转换

时间:2020-09-14 19:19:33

标签: rust

试图编写一个将向量填充范围内的泛型函数

fn fill_vec<T: From<usize> + Copy>(target: &mut Vec<T>, to: usize, step: usize) {
    let mut start  = 0_usize;
    for i in 0..to {
        if start >= to {
            break;
        } else {
            if start > 0 {
                target.push(T::from(start));
            }
            start += step;
        }
    };
}

但是我得到了错误


error[E0277]: the trait bound `i32: std::convert::From<usize>` is not satisfied
  --> src/main.rs:28:14
fill_vec(&mut target, 30, 4);
   |              ^^^^^^^^^^^ the trait `std::convert::From<usize>` is not implemented for `i32`

1 个答案:

答案 0 :(得分:0)

实际上,您不能从usize隐式转换为i32。 对于这种类型的转换(可能会导致截断),您 需要as关键字。

fn main() {
    let mut v: Vec<i32> = Vec::new();
    let a: usize = 123;

    // v.push(a);
    // expected `i32`, found `usize`

    // v.push(i32::from(a));
    // the trait `std::convert::From<usize>` is not implemented for `i32`

    v.push(a as i32); // cast
}

关于您的特定示例,使用num_traits条板箱可能会有所帮助。

fn fill_vec<T: num_traits::cast::FromPrimitive>(
    target: &mut Vec<T>,
    to: usize,
    step: usize,
) {
    let mut start = 0_usize;
    for i in 0..to {
        if start >= to {
            break;
        } else {
            if start > 0 {
                target.push(T::from_usize(start).unwrap());
            }
            start += step;
        }
    }
}
相关问题