gpt4 book ai didi

rust - 在 Rust 模式匹配中将变量绑定(bind)到文字

转载 作者:行者123 更新时间:2023-12-02 16:03:32 25 4
gpt4 key购买 nike

我有一个用 Rust 编写的状态机,它需要对两个状态执行相同的操作。

这两种状态都是枚举的变体,但包含不同数量的元素。

match self.state {
RunState::ACCUMULATE(byte, count) | RunState::ESCAPE(count) => todo!(),
_ => todo!()
}

该示例是无效的源代码,因为 byte 未绑定(bind)在所有模式中。

这可以通过将 byte 绑定(bind)到第二个模式中的文字零来解决,但我不知道如何存档。

我目前正在分别匹配这两种模式,这会导致我想避免的代码重复。

感谢您的关注。

最佳答案

模式旨在根据匹配的值按结构和绑定(bind)变量进行匹配。它不是为了引入任意绑定(bind)而设计的。您应该使用单独的 match 臂,如果您担心重复,也许可以使用辅助函数:

match self.state {
RunState::ACCUMULATE(byte, count) => helper(byte, count),
RunState::ESCAPE(count) => helper(0, count),
...
}

或者您可以为您的 enum 引入一个返回所需值的函数,例如:

impl RunState {
fn to_parts(&self) -> (u8, usize) { // or Option<(u8, usize)> if its not applicable to all
match self.state {
RunState::ACCUMULATE(byte, count) => (byte, count),
RunState::ESCAPE(count) => (0, count),
...
}
}
}

关于rust - 在 Rust 模式匹配中将变量绑定(bind)到文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70059012/

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