rust 如何参照修改`Option`中的值

ilmyapht  于 2023-10-20  发布在  其他
关注(0)|答案(1)|浏览(91)

给出一些大结构的选项列表:

struct big_struct {
    a:i32 // Imagine this is some big datatype
}

let mut tester:Vec<Option<(big_struct,big_struct)>> = vec![
    None,
    Some((big_struct{a:1},big_struct{a:2})),
    None,
];

我在这个列表上迭代,通过另一个检查,我知道哪些元素有Some,在这些元素上,我想调用一个函数来编辑它们的值
示例函数:

fn tester_method(pos:&mut (big_struct,big_struct)) {
    pos.0 = big_struct {a:8};
    pos.1 = big_struct {a:9};
}

无法工作的函数调用:tester_method(&mut tester[1].unwrap());
我该怎么做?
在函数调用时,我得到错误:

cannot move out of index of `std::vec::Vec<std::option::Option<(big_struct, big_struct)>>`
move occurs because value has type `std::option::Option<(big_struct, big_struct)>`, which does not implement the `Copy` traitrustc(E0507)
main.rs(132, 24): consider borrowing the `Option`'s content
qv7cva1a

qv7cva1a1#

调用:tester_method(tester[1].as_mut().unwrap());修复它。
.as_mut()

相关问题