来自有理数对象的整数输入的通用构造函数
Generic constructor from integer input for a Rational Number object
我正在实现一个供个人使用的有理数库,并且希望构造选项是 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>
bound on T
, but you're not actually using the trait: Replace input as i32
with input.into()
。
pub fn from_integer<T: Into<i32>>(input: T) -> Result<Self, String> {
Ok(Rational{
numerator: input.into(),
denominator: 1
})
}
我正在实现一个供个人使用的有理数库,并且希望构造选项是 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>
bound on T
, but you're not actually using the trait: Replace input as i32
with input.into()
。
pub fn from_integer<T: Into<i32>>(input: T) -> Result<Self, String> {
Ok(Rational{
numerator: input.into(),
denominator: 1
})
}