How to make these Trait calls a bit more intuitive? Or why do they work?

⚓ rust    📅 2025-07-02    👤 surdeus    👁️ 2      

surdeus

In the reference there is the snippet:

trait Num {
    fn from_i32(n: i32) -> Self;
}

impl Num for f64 {
    fn from_i32(n: i32) -> f64 { n as f64 }
}

// These 4 are all equivalent in this case.
let _: f64 = Num::from_i32(42);
let _: f64 = <_ as Num>::from_i32(42);
let _: f64 = <f64 as Num>::from_i32(42);
let _: f64 = f64::from_i32(42);

which i find quite helpful. However, the syntax for the first three let-statements is unintuitive to me.

Of course, I can just learn the fourth one; but for the other ones, it looks like magic that the compiler ends up using the type annotation to link it to the Self (of that's what seems to me.)

I'm sure there is some piece of knowledge I'm missing or not connecting to make it seem less magical and more attuned to the rest of the language patterns (at least basic ones I learnt.)

Edit: actually the 2 last statements are fine, because <f64 as X> is desambiguation and makes -some- sense to me.

6 posts - 4 participants

Read full topic

🏷️ rust_feed