Dissolve a Vec of known size

I have a Vec whose size I have already checked and I would like to take the sole element out from it:

let widgets = vec![1];
if widgets.len() == 0 {
  return Err(Box::from("No widgets"));
}
if widgets.len() > 1 {
  return Err(Box::from("Too many widgets"));
}

let widget = widgets[0];

The index operation doesn't work because elements can't be moved out from a Vec.

What's an idiomatic (and clone-free) way to get that one element while consuming the Vec?

v.into_inter().next().unwrap()

v.pop().unwrap()

2 Likes

Another option:

v.truncate(1); v.pop().unwrap()

Or, starting in 1.48,

v.truncate(1); let [first]: [_; 1] = v.try_into().unwrap();

Which, conveniently, will also work for sizes other than 1.

1 Like