英文:
Destructuring nested structs in Rust
问题
在Rust中,可以在嵌套的情况下解构结构体吗?
struct S2 {
field1: i64,
field2: i64,
}
struct S1 {
field1: String,
field2: S2,
}
let s1 = S1 {
field1: String::from("hello"),
field2: S2 {
field1: -1,
field2: 0,
}
}
let S1 {
field1,
field2: S2 {
field1: field1_s2,
..
}
} = s1;
我会假设答案是"不可以",但以防有类似的方法,或者我的语法可能有问题。
英文:
Is it possible to destructure structs in Rust when they are nested?
struct S2 {
field1: i64,
field2: i64,
}
struct S1 {
field1: String,
field2: S2,
}
let s1 = S1 {
field1: String::from("hello"),
field2: S2 {
field1: -1,
field2: 0,
}
}
let S1 {
field1,
S2 {
field1: field1_s2,
..
}
} = s1;
I would assume the answer is "no" - but just in case there is a way to do something similar, or perhaps my syntax is wrong.
答案1
得分: 7
这是可能的,但你需要指定字段名称:
let S1 {
field1,
field2: S2 {
field1: field1_s2, ..
},
} = s1;
英文:
Yes, this is possible, but you need to specify the field name:
let S1 {
field1,
field2: S2 {
field1: field1_s2, ..
},
} = s1;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论