【发布时间】:2020-11-22 01:16:36
【问题描述】:
我有一些原型代码:
impl MsgTrait for MsgA {
fn apply_to(&self, state: State) -> State {
match state {
State::StateOne(mut state_one) => {
state_one.common += 1; // just a mutability test
State::StateOne(state_one)
},
_ => {
state
}
}
}
}
impl MsgTrait for MsgB {
fn apply_to(&self, state: State) -> State {
match state {
State::StateOne(mut state_one) => {
state_one.common += 2; // just a mutability test
State::StateOne(state_one)
},
State::StateTwo(mut state_two) => {
state_two.common += 3; // just a mutability test
State::StateTwo(state_two)
}
}
}
}
// this is a stub for receiving different kinds of messages from the network
fn recv() -> Msg {
Msg::MsgA(Mega {field_a: 42})
}
fn main() {
let mut state = State::StateOne(StateOne {common: 0, one_special: 1});
for _ in 0..100 { // this would be loop, but that makes the playground timeout
let incoming = recv(); // this would block
match incoming {
Msg::MsgA(msg_a) => {
state = msg_a.apply_to(state)
},
Msg::MsgB(msg_b) => {
state = msg_b.apply_to(state)
}
}
}
}
为了改变 state 并在循环的下一次迭代中仍然拥有它,我已经开始从方法中返回它。
这是 Rust 的惯用语吗?
如果我确实需要这样做,有没有办法避免在每个方法中将 state_xxx 重新包装在 State::StateXxx(state_xxx) 中?
【问题讨论】:
-
通常这对于启用构建器模式和其他方法链接的方法来说是很常见的。重新包装是必要的,具体取决于您想要做什么。避免冗长的一种方法是在枚举上实现方法并让它们匹配并重新包装。
-
如果你不想为每个突变重建状态,你可以考虑传递一个可变引用。例如play.rust-lang.org/…
-
@possum 这正是我想要做的,我只是没有包含足够的
muts 来使其工作。如果您将此作为答案,我会接受。