Question about Traits vs Struct's associated method


#1

I have a question regarding traits and a struct’s associated methods

    trait Printable {
        fn print();
        fn another_print();
    }

    struct Foo;

    impl Foo {
        fn print() {
            println!("hello from Foo");
        }
    }

    impl Printable for Foo {
        fn print() {
            println!("hello from Printable");
        }
        fn another_print() {
            println!("hello from another Printable");
        }
    }

    fn main() {
        Foo::print();
        Foo::another_print();
    }

How do I invoke the print method of the Printable trait instead of the one defined in Foo?
Playground link


#2

I think it is called universal call syntax.

trait Printable {
    fn print();
    fn another_print();
}

struct Foo;

impl Foo {
    fn print() {
        println!("hello from Foo");
    }
}

impl Printable for Foo {
    fn print() {
        println!("hello from Printable");
    }
    fn another_print() {
        println!("hello from another Printable");
    }
}

fn main() {
    <Foo as Printable>::print();
    Foo::another_print();
}

#3

Wow. Thanks :slightly_smiling_face: @usamec

Do you know if there any docs on universal call syntax?


#4

Here you go:
https://doc.rust-lang.org/book/first-edition/ufcs.html