这是我的代码:

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

顺便说一下,物品.1是事务 struct 类型,而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 `()`

enter image description here enter image description here

为什么会这样,我如何修复它.

推荐答案

由于向量可能不包含item.0tx_id的项,因此您可能需要返回一个选项,如果未找到任何内容,则返回None.

类似这样:

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

Rust相关问答推荐

如何从Rust记录WASM堆内存使用情况?

为什么允许我们将可变引用转换为不可变引用?

如何为rust trait边界指定多种可能性

除了调用`waker.wake()`之外,我如何才能确保future 将再次被轮询?

当对VEC;U8>;使用serde_json时,Base64编码是保护空间的好方法吗?

`RwLockWriteGuard_,T`不实现T实现的特征

如何在函数中返回自定义字符串引用?

JSON5中的变量类型(serde)

如何将带有嵌套borrow /NLL 的 Rust 代码提取到函数中

通过mem::transmute将数组展平安全吗?

实现AsyncWrite到hyper Sender时发生生命周期错误

Rust 中 Mutex<> 的深拷贝?

push 方法是否取得所有权?

如何刷新 TcpStream

Rust 中的方法调用有什么区别?

If let expression within .iter().any

Rust 中的let是做什么的?

在 RefCell 上borrow

如何获取包裹在 Arc<> 和 RwLock<> 中的 Rust HashMap<> 的长度?

Rust 跨同一文件夹中文件的可见性