What type annotations does Rust want for this UFCS call?

家住魔仙堡 提交于 2019-12-24 15:10:03

问题


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.



来源:https://stackoverflow.com/questions/34374149/what-type-annotations-does-rust-want-for-this-ufcs-call

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!