What type annotations does Rust want for this UFCS

2019-08-12 08:35发布

问题:

Sorry, I'm probably missing something super obvious. I wonder why I can't call my trait method like this. Shouldn't this be the standard UFCS.

trait FooPrinter {
    fn print ()  {
        println!("hello");
    }
}

fn main () {
    FooPrinter::print();
}

Playpen: http://is.gd/ZPu9iP

I get the following error

error: type annotations required: cannot resolve `_ : FooPrinter`

回答1:

You cannot call a trait method without specifying on which implementation you wish to call it. It doesn't matter that the method has a default implementation.

An actual UFCS call looks like this:

trait FooPrinter {
    fn print()  {
        println!("hello");
    }
}

impl FooPrinter for () {}

fn main () {
    <() as FooPrinter>::print();
}

playground

If you don't need polymorphism on this method, move it to a struct or enum, or make it a global function.



标签: rust traits