tre*_*159 3 generics casting primitive-types rust
我是 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));
}
Run Code Online (Sandbox Code Playgroud)
Val*_*tin 11
最初的想法可能是需要U: Into<T>. 但是,没有eg,impl Into<i32> for f32所以这是行不通的。也可能会考虑 require T: Add<U, Output = T>,但是出于同样的原因,这在您的情况下也不起作用。
相反,您可以使用numcrate,特别是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_()
}
Run Code Online (Sandbox Code Playgroud)
通过该实现sum(),然后执行您的main()将输出以下内容:
23
13.11
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2629 次 |
| 最近记录: |