【问题标题】:Is there any trait that specifies numeric functionality?是否有任何特征可以指定数字功能?
【发布时间】:2026-02-02 02:05:01
【问题描述】:

我想使用一个特征来绑定一个泛型类型,比如这个假设的HasSQRT

fn some_generic_function<T>(input: &T)
where
    T: HasSQRT,
{
    // ...
    input.sqrt()
    // ...
}

【问题讨论】:

    标签: rust numeric generic-programming traits


    【解决方案1】:

    您可以使用numnum-traits crates,并将您的泛型函数类型与num::Floatnum::Integer 或任何相关特征绑定:

    use num::Float; // 0.2.1
    
    fn main() {
        let f1: f32 = 2.0;
        let f2: f64 = 3.0;
        let i1: i32 = 3;
    
        println!("{:?}", sqrt(f1));
        println!("{:?}", sqrt(f2));
        println!("{:?}", sqrt(i1)); // error
    }
    
    fn sqrt<T: Float>(input: T) -> T {
        input.sqrt()
    }
    

    【讨论】:

    • @HosseinNoroozpour 使用依赖项。 Rust 与许多其他语言的不同之处在于,包管理是内置的并被强烈接受。典型的例子是随机数生成,它在 crate 中而不是标准库中提供。
    • @HosseinNoroozpour 希望最小化依赖是可以理解的,但正如 Shepmaster 所说,Rust 使依赖管理变得方便,以鼓励人们使用它们。另外,num crate 维护得很好,不会被遗弃。
    • @Kroltan 我来自 C++ 背景,在那里添加每个依赖项都是一个可怕的决定。我猜想只有那些绑定到 C 库的库才是我应该避免添加的库,对吗?
    最近更新 更多