【问题标题】:Destructuring Complicated Return Types解构复杂的返回类型
【发布时间】:2021-05-26 21:40:47
【问题描述】:

大家好,我是 Rust 的新手,在过去的一周里,我一直在努力解决问题。我正在通过 odbc_iter crate 使用 ODBC 驱动程序查询 SQL 数据库。我试图解构它返回的内容。我不知道如何成功地做到这一点。我尝试将元素切碎并将其放入结构中,但没有运气。我试着让它保持原样,并按照我的逻辑去做,它很快就变得非常复杂。我非常感谢一个关于如何在 Rust 中管理这种情况的示例。

代码: '''

use odbc_iter::{Odbc, ValueRow, Column};
use chrono::NaiveDateTime;
fn main() {

    let key = "CONN_STR;";

    let mut connection = Odbc::connect(&key)
        .expect("failed to connect to database");

    let mut db = connection.handle();
    let query_result = db.query::<ValueRow>("EXEC dbo.BackupGet")
        .expect("failed to run query");

    for row in query_result {
        println!("{:?}", row.expect("failed to fetch row"))
    
    }
}

'''

输出: '''

[Some(Integer(5877)), Some(Timestamp(2021-05-26 13:30:55.827)), None, Some(String("Title here")), Some(Timestamp(2021-05-26 13:31:00.313)), Some(Timestamp(2021-05-26 13:47:25.053)), Some(String("Description here")), Some(Timestamp(2021-05-26 13:31:00.730)), Some(Timestamp(2021-05-26 13:31:05.013))]

[Some(Integer(5877)), Some(Timestamp(2021-05-26 13:30:55.827)), None, Some(String("Title here")), Some(Timestamp(2021-05-26 13:31:00.313)), Some(Timestamp(2021-05-26 13:47:25.053)), Some(String("Description here")), Some(Timestamp(2021-05-26 13:31:05.400)), Some(Timestamp(2021-05-26 13:32:00.097))]

''' 输出中还有 8 行相同格式的内容,但我省略了它,因此我不必为每一行清除所有敏感位。

【问题讨论】:

  • 您的代码库是否事先了解结果集的架构(即在编译期间)?

标签: rust odbc


【解决方案1】:

解构发生在编译时。您正在处理来自数据库的结果,它本质上是一个仅运行时的构造。具体来说,每一行都是Result&lt;ValueRow, ...&gt;,ValueRow依次是:

type ValueRow = Vec<Option<Value>>;

你不能解构。

正如您所提到的,解决此问题的唯一方法是(验证和)将数据放入 struct 中,然后您可以解构。

let FetchedData { a, b, c } = FetchedData::validate(row.unwrap()).unwrap();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-27
    • 2013-05-26
    • 2018-06-26
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多