我想写类似以下内容的东西:
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)
}
显然,Rust将从i32
到f32
进行转换时没有问题。是否有更好的编写方式?
self
,这样更有意义。 - StargateurPoint<T>
,所以我还没有self
。因此需要使用from<U>
作为构造函数。 - B_oldFrom
,因为没有From<i32> for f32
的实现,可能可以尝试这样做:https://play.integer32.com/?version=nightly&mode=debug&edition=2018&gist=6aea7192ed830c36aa2a53c31f219ff1,但要注意像我的例子所示,这可能会导致奇怪的行为。 - Stargateur