rust - 在 Rust 的模式匹配中键入注释?

标签 rust

我正在研究 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 error: unable to infer enough type information about _; type annotations or generic parameter binding required [E0282]

不幸的是,那个 crate 中的文档经常使用 unwrap,这对我没有帮助。在 Haskell 中,我会做类似 println!("{:?}", i::i32) 的事情,但我不知道如何在 Rust 中做。我已经尝试了各种方法来转换 row.take,但我一直没有成功。如果有更惯用的方法,我很乐意看到我可以用多种方式来构造此代码。

最佳答案

查看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 示例)。

关于rust - 在 Rust 的模式匹配中键入注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37755975/

相关文章:

rust - Rocket 0.5+ 中未使用异步?

generics - 使用类似泛型构造的子类型

rust - 有没有办法从 `f64::from(0.23_f32)` 得到 0.23_f64?

c - 将字符串从 Rust 传递到 C 会导致段错误或错误

rust - 在 Rust 的 HashMap<(String, usize), f64> 中查找键

rust - 在 Rust 中使用 UUID

rust - 如何迭代 Bevy 查询并保留对迭代值的引用以便稍后使用它?

sqlite - 使用rust 柴油 : SQLite INSERT RETURNING multiple ids

rust - 为实现 Trait 的类型实现 Borrow<Trait>

rust - Rust:在没有引用的情况下如何使用生命周期? [复制]