考虑以下示例:

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 => ...,
}

最佳答案

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

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

关于static - 静态特征功能的Rust类型提示,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28286960/

10-11 00:16