gpt4 book ai didi

generics - 如何在 Rust 中转换泛型原始类型?

转载 作者:行者123 更新时间:2023-11-29 08:26:32 24 4
gpt4 key购买 nike

<分区>

我想写如下内容:

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 特性不适用于 i32f32 的转换,这正是我最初想要的。

我能想到的最简单的解决方案是编写如下函数:

pub fn float2_from_int2(v: Point<i32>) -> Point<f32> {
Point::<f32>::new(v.x as f32, v.y as f32)
}

很明显,Rust 从 i32 转换为 f32 没有问题。有更好的写法吗?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com