วิธีแคสต์ระหว่างประเภท [ซ้ำ]
Sep 15 2020
กำลังพยายามเขียนฟังก์ชันทั่วไปโดยเติม Vector ในช่วง
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`
คำตอบ
prog-fh Sep 15 2020 at 03:04
แน่นอนคุณไม่สามารถแปลงจาก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;
}
}
}