如何将泛型转换为原始类型
How to cast a generic type to primitive type
我是 Rust 的新手。我不知道如何将通用类型 <T>
转换为原始类型。
有一个小例子,一个泛型类型的函数 sum:
fn sum<T: std::ops::Add<Output = T>, U>(x:T, y: U) -> T {
// is there any line of code similar to:
// x + y as T
x + y as T
// or check the type
// match type(x) {
// i32 => x + y as i32,
// i64 => x + y as i64,
// f32 => x + y as f32,
// _ => 0
// }
}
fn main() {
let a = 1;
let b = 22.22;
println!("{}", sum(a, b));
let a = 11.11;
let b = 2;
println!("{}", sum(a, b));
}
最初的想法可能是要求 U:
Into<T>
. However, there is no e.g. impl Into<i32> for f32
so that won't work. Might also think of requiring T:
Add<U, Output = T>
,但是出于同样的原因,这在您的情况下也行不通。
相反,您可以使用 num
crate, specifically the AsPrimitive
特征。
use std::ops::Add;
// num = "0.3"
use num::cast::AsPrimitive;
fn sum<T, U>(x: T, y: U) -> T
where
T: Copy + 'static,
T: Add<Output = T>,
U: AsPrimitive<T>,
{
x + y.as_()
}
使用 sum()
的实现,然后执行 main()
将输出以下内容:
23
13.11
我是 Rust 的新手。我不知道如何将通用类型 <T>
转换为原始类型。
有一个小例子,一个泛型类型的函数 sum:
fn sum<T: std::ops::Add<Output = T>, U>(x:T, y: U) -> T {
// is there any line of code similar to:
// x + y as T
x + y as T
// or check the type
// match type(x) {
// i32 => x + y as i32,
// i64 => x + y as i64,
// f32 => x + y as f32,
// _ => 0
// }
}
fn main() {
let a = 1;
let b = 22.22;
println!("{}", sum(a, b));
let a = 11.11;
let b = 2;
println!("{}", sum(a, b));
}
最初的想法可能是要求 U:
Into<T>
. However, there is no e.g. impl Into<i32> for f32
so that won't work. Might also think of requiring T:
Add<U, Output = T>
,但是出于同样的原因,这在您的情况下也行不通。
相反,您可以使用 num
crate, specifically the AsPrimitive
特征。
use std::ops::Add;
// num = "0.3"
use num::cast::AsPrimitive;
fn sum<T, U>(x: T, y: U) -> T
where
T: Copy + 'static,
T: Add<Output = T>,
U: AsPrimitive<T>,
{
x + y.as_()
}
使用 sum()
的实现,然后执行 main()
将输出以下内容:
23
13.11