gpt4 book ai didi

rust - 在 Rust 中返回提供的参数是惯用的吗?

转载 作者:行者123 更新时间:2023-12-03 11:45:05 24 4
gpt4 key购买 nike

我有一些原型(prototype)代码:

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)
}
}
}
}
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=e7ddbbe51ce02c66dc3203bc2ecec104
为了变异 state并且仍然为循环的下一次迭代拥有它,我已经开始从方法中返回它。
这是 Rust 的惯用语吗?
如果我确实需要这样做,有没有办法避免重新包装 state_xxxState::StateXxx(state_xxx)在每种方法中?

最佳答案

如果您不想为每个突变重建状态,则可以考虑改为传递可变引用。例如
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=74a8b1113204bc7abe31f9ced0851fd1

关于rust - 在 Rust 中返回提供的参数是惯用的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63204586/

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