Home > Software engineering >  How to compose trait operations in Rust without knowing the exact type
How to compose trait operations in Rust without knowing the exact type

Time:03-25

I'm creating a simple trait for natural numbers Nat with one implementation for 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.

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();
}

CodePudding user response:

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

  • Related