【问题标题】:Type annotation in a pattern match in Rust?在 Rust 的模式匹配中键入注释?
【发布时间】:2016-10-11 21:04:40
【问题描述】:

我正在深入研究 Rust,特别是优雅地处理错误,但我在类型推断方面遇到了一点麻烦。

extern crate mysql;

use mysql as my;

fn main() {
    my_test();
}

fn my_test() -> Result<(), my::Error> {
    let pool = try!(my::Pool::new(""));
    let res = try!(pool.prep_exec("select 1 as count", ()));
    for rows in res {
        let row: my::Row = try!(rows);
        match row.take("count") {
            None => (),
            Some(i) => println!("{:?}", i),
        };
    }
    Ok(())
}

导致

src/bin/main.rs:86:12: 86:13 错误:无法推断出关于_ 的足够类型信息;需要类型注释或泛型参数绑定 [E0282]

不幸的是,那个箱子里的文档经常使用unwrap,这对我没有帮助。在 Haskell 中,我会做类似 println!("{:?}", i :: i32) 的事情,但我不知道如何在 Rust 中做到这一点。我尝试了各种方法来投射row.take,但我没有任何运气。如果有更惯用的方式,我很乐意看到我可以用多种方式来构建这段代码。

【问题讨论】:

  • 请注意,这只是一个问题,因为您使用的是println!,它接受的值范围很广。如果您要在某些限制类型的上下文中使用 i 值(例如通过将其传递给函数),则可以推断出类型。

标签: rust


【解决方案1】:

查看Row::take 文档,我们可以看到两种类型的参数TII 类型是从 "count" 参数推断出来的,T 类型用于返回类型。我们有两个选项来指定返回类型,explicit 在方法调用中,或者隐含在变量的类型中(就像你对 row 所做的那样):

fn my_test() -> Result<(), my::Error> {
    let pool = try!(my::Pool::new(""));
    let res = try!(pool.prep_exec("select 1 as count", ()));
    for rows in res {
        let mut row: my::Row = try!(rows);
        // specify type T explicitly, let type I to be inferred
        match row.take::<i32, _>("count") {
            None => (),
            Some(i) => println!("{:?}", i),
        };
        // or
        let s: Option<i32> = row.take("count");
    }
    Ok(())
}

type ascription RFC 提出了一种语法(类似于 Haskell 示例),用于用类型注释子表达式。

【讨论】:

    【解决方案2】:

    可以在匹配模式中的Option&lt;T&gt;Result&lt;T, E&gt; 变体上注释类型。

    对于选项,

    match row.take("count") {
        None => (),
        Some::<i32>(i) => println!("{:?}", i),
    }
    

    或者如果你的函数返回一个结果,

    match row.take("count") {
        Err(e) => panic!("{:?}", e),
        Ok::<i32, _>(i) => println!("{:?}", i),
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多