尽管返回了所需的值,为什么我的代码仍返回“()”?

3 rust

这是我的代码:

fn fetch_transaction (graph: &mut Vec<(&'static str, Transaction)>, tx_id: &'static str) -> Transaction {
    for item in graph.iter() {
        if item.0 == tx_id {
            return item.1;
        } else {
            println!("Transaction not found.");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

顺便说一下,item.1 是一个 Transaction 结构类型,而 item.0 是一个静态字符串。当我编译它时,我收到此错误:

fn fetch_transaction (graph: &mut Vec<(&'static str, Transaction)>, tx_id: &'static str) -> Transaction {
   |                                                                                               ----------- expected `Transaction` because of return type
54 | /     for item in graph.iter() {
55 | |         if item.0 == tx_id {
56 | |             return item.1;
57 | |         } else {
58 | |             println!("Transaction not found.");
59 | |         }
60 | |     }
   | |_____^ expected struct `Transaction`, found `()`
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述 在此输入图像描述

这是为什么,我该如何解决它。

小智 5

由于向量可能不包含item.0is的项目tx_id,因此您可能想要做的是返回一个 Option,如果None未找到任何内容,则返回 Option。

像这样的东西:

fn fetch_transaction(graph: &mut Vec<(&'static str, Transaction)>, tx_id: &'static str) -> Option<Transaction> {
    graph.iter().find(|i| i.0 == tx_id).and_then(|i| Some(i.1))
}
Run Code Online (Sandbox Code Playgroud)