rust - Rust 需要为这个 UFCS 调用添加什么类型的注解?

标签 rust traits

抱歉,我可能遗漏了一些非常明显的东西。我想知道为什么我不能这样调用我的特征方法。这不应该是标准的 UFCS 吗?

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

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

围栏:http://is.gd/ZPu9iP

出现以下错误

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

最佳答案

如果不指定要调用哪个实现,就不能调用特征方法。该方法是否具有默认实现并不重要。

实际的 UFCS 调用如下所示:

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

impl FooPrinter for () {}

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

playground

如果您不需要此方法的多态性,请将其移至structenum,或将其设为全局函数。

关于rust - Rust 需要为这个 UFCS 调用添加什么类型的注解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34374149/

相关文章:

scala - 如何模式匹配扩展多个特征的对象?

struct - 何时使用引用或框来拥有实现结构中特征的字段?

function - 在 Rust 中,什么是 `fn() -> ()` ?

rust - 是否有可能在 U 和 V 上有一个通用的结构,其中 U : V?

rust - use 和 extern crate 有什么区别?

rust - f32 没有实现减法?

generics - 在不使用关联类型的情况下简化类型签名

windows - 如何根据操作系统系列具有不同的依赖关系

rust - 如何配置 actix-web 以接受来自任何来源的 CORS 请求?

rust - 为什么该特征没有实现?