【发布时间】:2017-09-25 05:40:15
【问题描述】:
我有一个结构
struct Foo {
foo1: String,
foo2: String,
foo3: String,
foo4: String,
// ...
}
我想从一个向量创建一个Foo 的实例。
let x = vec!["a".to_string(), "b".to_string(), "c".to_string(), "d".to_string()];
match x.as_slice() {
&[ref a, ref b, ref c, ref d] => {
let foo = Foo {
foo1: a.to_string(),
foo2: b.to_string(),
foo3: c.to_string(),
foo4: d.to_string(),
};
},
_ => unreachable!(),
}
我必须复制字符串吗?有没有更好的方法将向量解构为a、b、c、d 以及转移所有权?
其实我不介意x在解构后被完全销毁。所以我希望除了切片之外的向量也有模式匹配。目前看来我们只能解构切片。
【问题讨论】:
-
Compilable example 用于实验。
标签: rust