结构类枚举变体中的更新字段 [英] Update field in struct-like enum variant
本文介绍了结构类枚举变体中的更新字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以使用一个struct结构体的struct update语法,但是我不能使用类似于struct的枚举变体。我也不能用点语法从一个类似结构体的枚举变体更新一个字段。
I am able to use the struct update syntax with a single struct, but I am not able to use it with a struct-like enum variant. Neither can I update a field from a struct-like enum variant with the dot syntax.
例如:
enum Enum {
Struct {
field1: i32,
field2: i32,
}
}
fn main() {
let mut my_enum = Enum::Struct {
field1: 1,
field2: 2,
};
my_enum = Enum::Struct {
field1: 1,
.. my_enum
};
my_enum = match my_enum {
strct@Enum::Struct { field1, field2 } => Enum::Struct {
field1: 1,
.. strct
},
};
}
两种方式都给我一个错误:
Both ways give me an error:
functional record update syntax requires a struct
这段代码:
my_enum.field1 = 3;
给我以下错误:
attempted access of field `field1` on type `Enum`, but no field with that name was found
如何从结构体类型的枚举变体更新一个字段?
How can I update a field from a struct-like enum variant?
推荐答案
这样做:
match my_enum {
Enum::Struct { ref mut field1, .. } => {
*field1 = 3;
}
}
这篇关于结构类枚举变体中的更新字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文