我正在实现一个供个人使用的有理数库,并且希望构造选项为 from_integer,其中该方法采用能够转换为 i32 的任何数据类型。我尝试了以下
pub fn from_integer<T: Into<i32>>(input: T) -> Result<Self, String> {
Ok(Rational{
numerator: input as i32,
denominator: 1
})
}
但得到这个错误non-primitive cast: `T` as `i32`
an `as` expression can only be used to convert between primitive types or to coerce to a specific trait objectrustc(E0605)
lib.rs(97, 24): an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
我是否有错误的特征,或者我应该以不同的方式表达我希望以这种方式输入输入?
最佳答案
as
对泛型总是没用的。
您拥有 Into<i32>
已经是正确的了绑定(bind) T
,但您实际上并没有使用特征:替换 input as i32
与 input.into()
.
pub fn from_integer<T: Into<i32>>(input: T) -> Result<Self, String> {
Ok(Rational{
numerator: input.into(),
denominator: 1
})
}
关于generics - 有理数对象的整数输入的通用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65818231/