在Rust中的match语句中解构Option<Box<_>>

我有一个大物体需要装在另一个物体中,但我不一定总是需要它。所以我想使用 if 语句来获取可选的盒装 TempStructure,但我不确定如何同时解构和取消引用。

例子:

pub struct TempStructure {
    lots_of_data: [u64; 64],
}
pub struct Structure {
    pending_removal: Option<Box<(TempStructure, bool)>>,
}
impl Structure {
    pub fn do_somthing(&mut self) {
        // How do I destructure the Option and dereference the Box to get TempStructure?
        if let Some((temp_structure, some_boolean)) = self.pending_removal.take() { 
            // Do something with temp_structure and some_boolean
        }
    }
}

当我这样做 ^^^ 我得到一个expected struct `std::boxed::Box`, found tuple错误。

回答

匹配后取消引用框:

if let Some(inner) = self.pending_removal.take() {
    let (temp_structure, some_boolean) = *inner;
    // Do something with temp_structure and some_boolean
}

(操场)

如果您认为这有点笨拙,那么您是对的。在夜间,您可以使用不稳定box_patterns功能为此启用更好的语法(尽管这可能永远不会稳定):

if let Some(box (temp_structure, some_boolean)) = self.pending_removal.take() {
    // Do something with temp_structure and some_boolean
}

(操场)


回答

您可以通过在.as_deref()之后添加 a 来解决此问题take()

pub struct TempStructure {
    lots_of_data: [u64; 64],
}
pub struct Structure {
    pending_removal: Option<Box<(TempStructure, bool)>>,
}
impl Structure {
    pub fn do_somthing(&mut self) {
        // How do I destructure the Option and dereference the Box to get TempStructure?
        if let Some((temp_structure, some_boolean)) = self.pending_removal.take().as_deref() { 
            // Do something with temp_structure and some_boolean
        }
    }
}

Box<T>取消引用&Tas_deref()取消引用 的值Option,因此它会给您一个&T超出您的Option<Box<T>>.

编辑:另一种选择是取消引用 Box 以将值移出它:

        if let Some((temp_structure, some_boolean)) = self.pending_removal.take().map(|boxed| *boxed) { 
            // assignments just for demonstration purposes that we now get
            // owned values rather than references.
            let _: TempStructure = temp_structure;
            let _: bool = some_boolean;
        }

  • I don't think comments are supposed to have multiline code blocks.
    https://meta.stackexchange.com/questions/39260/how-do-i-post-code-in-comments

以上是在Rust中的match语句中解构Option&lt;Box&lt;_&gt;&gt;的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>