本文介绍了如何在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
查看
示例(您可以避免使用AsPrimitive选项):
you can use ToPrimitive trait from num
example (you can avoid Option with 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);
}
这篇关于如何在Rust中转换泛型基本类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!