我想写如下内容:
pub struct Point<T> {
pub x: T,
pub y: T,
}
impl<T> Point<T> {
pub fn from<U>(other: Point<U>) -> Point<T> {
Point {
x: other.x as T,
y: other as T,
}
}
}
这不可能:
error[E0605]: non-primitive cast: `U` as `T`
--> src/lib.rs:9:16
|
9 | x: other.x as T,
| ^^^^^^^^^^^^
|
= note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait
看着如果我知道这是可能的,如何将通用 T 转换为 f32? https://stackoverflow.com/questions/35766261/how-do-i-cast-generic-t-to-f32-if-i-know-that-its-possible,我了解到From
特质不适用于i32
to f32
转换,这就是我最初想要的。
我能想到的最简单的解决方案是编写一个如下函数:
pub fn float2_from_int2(v: Point<i32>) -> Point<f32> {
Point::<f32>::new(v.x as f32, v.y as f32)
}
显然 Rust 没有任何问题i32
to f32
。有更好的方法来写这个吗?
您可以使用到原语 https://docs.rs/num/0.2.0/num/trait.ToPrimitive.html特质来自num https://crates.io/crates/num
示例(您可以避免使用 AsPrimitive 选项):
pub struct Point<T> {
pub x: T,
pub y: T,
}
impl<T: Copy + 'static> Point<T> {
pub fn from<U: num::cast::AsPrimitive<T>>(other: Point<U>) -> Point<T> {
Point {
x: other.x.as_(),
y: other.y.as_(),
}
}
}
fn do_stuff() {
let a = Point{x: 0i32, y: 0i32};
let b = Point::<f32>::from(a);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)