Why is my code returning '()' despite returning the required value?

Viewed 75

Here is my code:

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.");
        }
    }
}

By the way, item.1 is a Transaction struct type, while item.0 is a static string. When I compile it, I get this error:

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 `()`

enter image description here enter image description here

Why is this, and how can I fix it.

1 Answers

Since it is possible that the vector does not contain an item whose item.0 is tx_id, what you probably want to do is return an Option, which will be None if nothing was found.

Something like this:

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))
}
Related