I want to do something like this:
enum Foo {
Empty,
Single(String),
Multiple(Vec<String>),
}
fn convert(xs: Vec<String>) -> Foo {
match xs {
[] => Foo::Empty,
[x] => Foo::Single(x),
xs => Foo::Multiple(xs),
}
}
The problems:
- A
Vec
is not an array, so the above code wouldn't compile.
- Using slice would require cloning.
kornel
2
That's not possible. From Rust's perspective Vec
is just a 3-element struct
, and Rust doesn't even know it has content.
Write if
/else
instead.
1 Like
The closest I can come up with is this:
fn convert(mut xs: Vec<String>) -> Foo {
match xs.len() {
0 => Foo::Empty,
1 => Foo::Single(xs.pop().unwrap()),
_ => Foo::Multiple(xs),
}
}
1 Like
trentj
4
fn convert(mut xs: Vec<String>) -> Foo {
match &mut *xs {
[] => Foo::Empty,
[x] => Foo::Single(std::mem::take(x)),
_ => Foo::Multiple(xs),
}
}
2 Likes
system
Closed
5
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.