【问题标题】:Rust type hint for static trait function静态特征函数的 Rust 类型提示
【发布时间】:2015-02-02 21:18:52
【问题描述】:

考虑这个例子:

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

【问题讨论】:

标签: static rust traits


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 2022-07-31
    相关资源
    最近更新 更多