简体   繁体   English

如何在不知道确切类型的情况下在 Rust 中组合特征操作

[英]How to compose trait operations in Rust without knowing the exact type

I'm creating a simple trait for natural numbers Nat with one implementation for u64 .我正在为自然数Nat创建一个简单的特征,并使用u64的一个实现。 When I use this trait and use one operation with a type annotation, it figures out what implementation to use.当我使用这个特性并使用一个带有类型注释的操作时,它会找出要使用的实现。 However, when I specify a type for a composite expression, Rust is unable to compile the expression.但是,当我为复合表达式指定类型时,Rust 无法编译该表达式。

pub trait Nat {
    fn one() -> Self;
    fn succ(self) -> Self;
}

impl Nat for u64 {
    fn one() -> Self { 1 }
    fn succ(self) -> Self { return self + 1; }
}

#[test]
fn test_adder() {
    // Works well
    assert_eq!(4, 3.succ());
    let just_1: u64 = Nat::one();
    assert_eq!(just_1, 1);

    // Doesn't work
    let just_2: u64 = Nat::one().succ();
}

You can make a fully qualified call specifiying the type:您可以进行指定类型的完全限定调用:

let just_2: u64 = <u64 as Nat>::one().succ();

or just use the type itself and let the compiler infer the trait method:或者只使用类型本身,让编译器推断特征方法:

let just_2: u64 = u64::one().succ();

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM