如何铸造我知道是整数的通用类型? [英] How to cast generic types that I know to be integers?
问题描述
我想以通用方式检查C API的返回代码,结果必须没有C类型,例如 libc :: c_int
。有任何方法可以写一个函数
I want to check return codes of C APIs in a generic way and the result must be free from C types such as libc::c_int
. Are there any ways to write a function like
fn check<S: PartialOrd + std::num::Zero, T> (x: S) -> Option<T> {
if std::num::zero::<S>() <= x { Some(x as T) }
else { None }
}
< c> T 是 check()
的所有用法的整数类型?编译器拒绝我的代码抱怨错误:非标量转换:`S`为`T`
when I'm sure that S
and T
are integral types for all usages of check()
? The compiler rejects my code complaining error: non-scalar cast: `S` as `T`
推荐答案
为Rust 1.x更新
不可能将任意类型转换为任意类型, (几乎)你想要做什么。您需要在类型约束和转换操作中更具体。
It is impossible to cast arbitrary type to arbitrary type, and that's exactly (almost) what you're trying to do. You need to be more specific in type constraints and conversion operations.
extern crate num;
use num::{Zero, NumCast};
fn check<S: PartialOrd+Zero+NumCast, T: NumCast>(x: S) -> Option<T> {
if x >= S::zero() { Some(num::cast(x).unwrap()) }
else { None }
}
fn main() {
let x: i8 = 10;
let y: Option<i32> = check(x);
println!("{:?}", y);
let x: i8 = -10;
let y: Option<i32> = check(x);
println!("{:?}", y);
}
这里我使用了一个特殊的特征: num :: traits :: NumCast
from num
crate,它为所有基本类型实现,并提供了一个静态方法,可以从任何实现 num :: ToPrimitive
。 num
crate还提供了一个函数, num :: cast()
,它提供了一个简单的界面来执行数值转换。
Here I'm using a special trait, num::traits::NumCast
from num
crate, which is implemented for all primitive types and provides a static method which converts to these types from anything which implements num::ToPrimitive
. num
crate also provides a function, num::cast()
, which gives a simple interface to perform numeric casts.
请注意, cast(x)
返回选项< T>
;它返回无
如果 x
无法在目标类型中表示。我在这里使用 unwrap()
,因为在你的情况下,根据你的描述,无法正确转换值可能是一个编程错误,所以失败的任务感觉更合适。也可以直接写 cast(x)
:
Note that cast(x)
returns Option<T>
; it returns None
if x
can't be represented in the target type. I'm using unwrap()
here because in your case, according to your description, inability to convert a value correctly is likely a programming error, so failing the task feels more appropriate. It is also possible to write cast(x)
directly:
if x >= S::zero() { num::cast(x) }
...
在这种情况下, check()
不仅会返回 None
如果不可能将参数转换为结果类型。
In this case check()
will return None
not only when its argument is negative, but also if it is impossible to convert the argument to the result type.
这篇关于如何铸造我知道是整数的通用类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!