如何在选项数组中正确重新分配值?



尝试更新选项数组中的值:

static mut ILIST: [Option<u32>; 5] = [None, None, None, None, None];
fn main() {
unsafe {
ILIST[0] = Some(10);
match &ILIST[0].as_mut() {
None => println!("Is none"),
Some(n) => {
*n = 5;
},
}
match ILIST[0] {
None => println!("Is none"),
Some(n) => {
assert_eq!(n, 5);
},
}
}
}

给出以下编译器错误:

error[E0308]: mismatched types
--> src/main.rs:17:10
|
17 |                 *n = 5;
|                      ^ expected `&mut u32`, found integer
|
help: consider dereferencing here to assign to the mutable borrowed piece of memory
|
17 |                 **n = 5;
|                 ^^^

将指定的代码更新为以下内容:

Some(n) => {
**n = 5;
},

导致另一个编译器错误:

error[E0594]: cannot assign to `**n` which is behind a `&` reference
--> src/main.rs:17:5
|
17 |                 **n = 5;
|                 ^^^^^^^ `n` is a `&` reference, so the data it refers to cannot be written

对这里出了什么问题有什么见解吗?谢谢!

你不需要引用:

static mut ILIST: [Option<u32>; 5] = [None, None, None, None, None];
fn main() {
unsafe {
ILIST[0] = Some(10);
// not a ref
match ILIST[0].as_mut() {
None => println!("Is none"),
Some(n) => *n = 5,
}
match ILIST[0] {
None => println!("Is none"),
Some(n) => assert_eq!(n, 5),
}
}
}

最新更新