重命名匹配中的枚举字段 (rust)
Rename enum fields in match (rust)
我在枚举上有一个匹配块,其中一个匹配案例包含同一枚举上的另一个匹配块。像这样:
fn foo(&mut self, scenario: &mut Scenario) -> Result<&mut Self>
{
match self {
Scenario::Step { attributes, .. } => {
match scenario {
Scenario::Step { attributes,.. } => {
有没有办法访问内部匹配中的两个 attributes
字段?我看到了 return 内部匹配块中那个字段的可能性,但是它可以用更漂亮的方式处理吗?
您可以在一个元组中同时匹配它们:
fn foo(&mut self, scenario: &mut Scenario) -> Result<&mut Self> {
match (self, escenario) {
(Scenario::Step { attributes, .. }, Scenario::Step { attributes: attributes2, .. }) => {}
}
}
您可以像这样重命名匹配的变量:
fn foo(&mut self, scenario: &mut Scenario) -> Result<&mut Self>
{
match self {
Scenario::Step { attributes: attrs1, .. } => {
match scenario {
Scenario::Step { attributes: attrs2,.. } => {
// do something with attrs1 and attrs2
更好的是,您可以在元组中匹配它们:
fn foo(&mut self, scenario: &mut Scenario) -> Result<&mut Self>
{
match (self, scenario) {
(Scenario::Step { attributes: attrs1, .. }, Scenario::Step { attributes: attrs2,.. }) => {
// do something with attrs1 and attrs2
我在枚举上有一个匹配块,其中一个匹配案例包含同一枚举上的另一个匹配块。像这样:
fn foo(&mut self, scenario: &mut Scenario) -> Result<&mut Self>
{
match self {
Scenario::Step { attributes, .. } => {
match scenario {
Scenario::Step { attributes,.. } => {
有没有办法访问内部匹配中的两个 attributes
字段?我看到了 return 内部匹配块中那个字段的可能性,但是它可以用更漂亮的方式处理吗?
您可以在一个元组中同时匹配它们:
fn foo(&mut self, scenario: &mut Scenario) -> Result<&mut Self> {
match (self, escenario) {
(Scenario::Step { attributes, .. }, Scenario::Step { attributes: attributes2, .. }) => {}
}
}
您可以像这样重命名匹配的变量:
fn foo(&mut self, scenario: &mut Scenario) -> Result<&mut Self>
{
match self {
Scenario::Step { attributes: attrs1, .. } => {
match scenario {
Scenario::Step { attributes: attrs2,.. } => {
// do something with attrs1 and attrs2
更好的是,您可以在元组中匹配它们:
fn foo(&mut self, scenario: &mut Scenario) -> Result<&mut Self>
{
match (self, scenario) {
(Scenario::Step { attributes: attrs1, .. }, Scenario::Step { attributes: attrs2,.. }) => {
// do something with attrs1 and attrs2