【发布时间】:2019-04-26 12:11:47
【问题描述】:
我想写如下内容:
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
查看How do I cast generic T to f32 if I know that it's possible?,我了解到From trait 不适用于i32 到f32 的转换,这正是我最初想要的。
我能想出的最简单的解决方案是编写如下函数:
pub fn float2_from_int2(v: Point<i32>) -> Point<f32> {
Point::<f32>::new(v.x as f32, v.y as f32)
}
显然,Rust 从i32 转换为f32 没有问题。有没有更好的写法?
【问题讨论】:
-
注意你应该带
self,这样更有意义 -
您能详细说明一下吗?我还没有
self,因为我刚要创建Point<T>。因此from<U>,可以说是构造函数。 -
我不建议您实施
From有一个原因是没有From<i32> for f32实施,也许这样做,play.integer32.com/…,但请注意,就像我的示例节目一样,这可能会导致奇怪的行为。