generics - 有理数对象的整数输入的通用构造函数

标签 generics rust casting traits

我正在实现一个供个人使用的有理数库,并且希望构造选项为 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/

相关文章:

c# - 通用所有控件方法

rust - 我如何将参数从函数传递到宏

C++ - 将 float 组转换为 std::string

delphi - TFunc<T> - 有什么方法可以传递输入参数修饰符吗?

java - 为什么 Java 不解析这个 <generic> 方法签名?

module - 有没有办法在公共(public)特征中具有私有(private)功能?

mongodb - 使用 mongodb-1.2.2 和 Rocket-0.5.0-rc.1 时如何解决异步不兼容问题?

java - 在 websphere IBM 中错误地将 varchar 转换为 date

Golang - 将 uint 转换为 os.FileMode

java - 通用 HashMap