gpt4 book ai didi

memory-management - 使用 Option<&mut> 2 次

转载 作者:行者123 更新时间:2023-11-29 08:23:03 25 4
gpt4 key购买 nike

下面的程序可以正常编译:

fn write_u16(bytes: &mut Vec<u8>, value: u16) {
bytes.push((value >> 8) as u8);
bytes.push(value as u8);
}

fn write_u32(bytes: &mut Vec<u8>, value: u32) {
write_u16(bytes, (value >> 16) as u16);
write_u16(bytes, value as u16);
}

现在我将字节类型更改为 Option<&mut Vec>:

fn write_u16(bytes_opt: Option<&mut Vec<u8>>, value: u16) {
if let Some(bytes) = bytes_opt {
bytes.push((value >> 8) as u8);
bytes.push(value as u8);
}
}

fn write_u32(bytes_opt: Option<&mut Vec<u8>>, value: u32) {
write_u16(bytes_opt, (value >> 16) as u16);
write_u16(bytes_opt, value as u16);
}

程序现在无法编译:

main.rs:10:15: 10:24 error: use of moved value: `bytes_opt`
main.rs:10 write_u16(bytes_opt, value as u16);
^~~~~~~~~
main.rs:9:15: 9:24 note: `bytes_opt` moved here because it has type `core::option::Option<&mut collections::vec::Vec<u8>>`, which is non-copyable
main.rs:9 write_u16(bytes_opt, (value >> 16) as u16);
^~~~~~~~~
error: aborting due to previous error

我不太明白,为什么我不能两次使用Option,我该如何解决这个问题?

我能想到的解决这个问题的唯一方法是:

fn write_u32(bytes_opt: Option<&mut Vec<u8>>, value: u32) {
if let Some(bytes) = bytes_opt {
write_u16(Some(bytes), (value >> 16) as u16);
write_u16(Some(bytes), value as u16);
} else {
write_u16(None, (value >> 16) as u16);
write_u16(None, value as u16);
}
}

但这不是很好的代码。

最佳答案

虽然我怀疑在这种情况下你不应该这样做(正如已经评论过的那样),但在这种情况下可以安全地重新借用可变引用:

fn write_u32(mut bytes_opt: Option<&mut Vec<u8>>, value: u32) {
write_u16(bytes_opt.as_mut().map(|x| &mut **x), (value >> 16) as u16);
write_u16(bytes_opt, value as u16);
}

bytes_opt.as_mut().map(|x| &mut **x) 也可以这样写 match bytes_opt { Some(&mut ref mut x) => Some(x) , 无 => 无, }。一个非常令人费解的模式(从左到右阅读它:&mut——解引用包含的值,ref mut——然后​​对其进行新的可变引用),但是它有效并避免了所有权问题。

关于memory-management - 使用 Option<&mut> 2 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29335173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com