rust - if let Some 和 match 的区别
问题描述
试图了解哪里出了问题
fn set_inpt_port_values1(&mut self, input_port_values: HashMap<u8, u8>) {
if let Some(mut io_handler) = self.io_handler {
io_handler.set_input_ports_values(input_port_values);
}
}
得到
cannot move out of `self.io_handler.0` which is behind a mutable referencerustcE0507
i808x.rs(2333, 21): data moved here
i808x.rs(2333, 21): move occurs because `io_handler` has type `Box<dyn IoHandler>`, which does not implement the `Copy` trait
i808x.rs(2333, 39): consider borrowing here
另一方面,类似的功能
fn set_inpt_port_values(&mut self, input_port_values: HashMap<u8, u8>) {
match &mut self.io_handler {
Some(io_handler) => {
io_handler.set_input_ports_values(input_port_values);
}
_ => (),
}
}
可以正常工作/编译(可能set_inpt_port_values
不需要可变)。
io_handler 字段是Option<Box<dyn IoHandler>>
pub trait IoHandler {
fn in_op(&mut self, port: u8) -> u8;
fn out_op(&mut self, port: u8, byte: u8);
fn set_input_ports_values(&mut self, input_port_values: HashMap<u8, u8>);
}
解决方案
好吧,在这个声明中
if let Some(mut io_handler) = self.io_handler {
您正试图self.io_handler
进入一个名为io_handler
. 这是不允许的,因为这会导致self.io_handler
未初始化。
另一方面,这match
match &mut self.io_handler {
Some(io_handler) => {
匹配 a&mut Option<Box<dyn IoHandler>>
并将可变引用移动到self.io_handler
名为 的不可变变量io_handler
中。
您可以使用 if let 来实现相同的目的,方法是使用以下ref
关键字:
if let Some(ref mut io_handler) = self.io_handler {
这现在将尝试借用对该框内任何内容的可变引用。
推荐阅读
- swift - Swift Binary Search 失败到最后一个 return 语句
- python - 与两列中的 id 关联的所有值的滚动总和
- java - 在android运行时java中编译java文件
- javascript - mvc asp 无法使用我认为的查询进行更新
- wpf - 为什么依赖属性不能在用户控件中使用?
- hyperledger-composer - failed to install composer-cli but I see errors
- android - 我的按钮代码在 Android Studio 中不断给我错误
- eclipse - 如何在 MyEclipse 中手动安装 IvyDE?
- reactjs - React 类组件具有属性,但 Typescript 说它没有
- arduino - 调用 void 函数 arduino