Rust类型提示静态特征函数

时间:2015-02-02 21:18:53

标签: static rust traits

考虑这个例子:

trait MyTrait {
    fn maybe_new() -> Option<Self>;
}

impl MyTrait for i32 {...}

fn hello() {
    match MyTrait::maybe_new() {
        Some(x) => ...,
        None => ...,
    }
}

这无法编译,因为无法推断x的类型。有没有办法添加一个类型注释来使这个工作,而不必将maybe_new()分解为像这样的let语句?:

let p:Option<i32> = MyTrait::maybe_new();
match p {
    Some(x) => ...,
    None => ...,
}

1 个答案:

答案 0 :(得分:3)

How do I provide type annotations inline when calling a non-generic function?。在你的情况下,它看起来像这样:

match <i32 as MyTrait>::maybe_new() {
    Some(x) => ...,
    None => ...,
}