generics - 如何在 Rust 中转换泛型原始类型?
问题描述
我想写如下内容:
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?,我了解到该From
特征不适用于i32
转换f32
,这是我最初想要的。
我能想到的最简单的解决方案是编写如下函数:
pub fn float2_from_int2(v: Point<i32>) -> Point<f32> {
Point::<f32>::new(v.x as f32, v.y as f32)
}
i32
显然,Rust 从to转换没有问题f32
。有没有更好的方法来写这个?
解决方案
您可以使用num示例中的ToPrimitive特征
(您可以避免使用 AsPrimitive 的 Option):
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);
}
推荐阅读
- oop - kotlin 类构造函数参数的默认值类型是什么?
- java - 会话在android的webView中不起作用
- mysql - 具有不同类别的每列的子查询的 Mysql 查询
- c++ - 为指针静态分配内存与为指针删除动态分配内存有什么区别?
- unit-testing - How can i test a function that return a promise or reject - Jasmine and Karma
- python - 如何使用pycharm删除mongodb中文档的重复
- networking - 如何在statnet的二分网络中仅将顶点属性分配给一种模式?
- c++ - 调试BFS,计算直到所有橘子都烂掉的最短时间
- firebase - 如何以最少的小部件重新构建和 Firestore 读取来使用 StreamProvider?
- python - Django session deletion effects another django application