在 Rust 中返回提供的参数是惯用的吗?
Is returning the supplied argument idiomatic in Rust?
我有一些原型代码:
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)
中?
如果您不想为每个突变重建状态,您可以考虑传递一个可变引用。例如
我有一些原型代码:
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)
中?
如果您不想为每个突变重建状态,您可以考虑传递一个可变引用。例如