How can I unpack (destroy) elements from a vector?

I am currently doing the following:

let line_parts = line.split_whitespace().take(3).collect::<Vec<&str>>(); let ip = line_parts[0]; let bytes = line_parts[1]; let int_number = line_parts[2]; 

Is it possible to do something like this?

 let [ip, bytes, int_number] = line.split_whitespace().take(3).collect(); 

I have noticed various links to vector destructuring on some sites, but white papers do not seem to mention this.

+5
source share
1 answer

It seems that you need "fragments":

 #![feature(slice_patterns)] fn main() { let line = "127.0.0.1 1000 what!?"; let v = line.split_whitespace().take(3).collect::<Vec<&str>>(); if let [ip, port, msg] = &v[..] { println!("{}:{} says '{}'", ip, port, msg); } } 

Pay attention to if let instead of the usual let . Slice patterns are rebuttable, so we need to consider this (you might want to have an else branch).

This will require a nightly version of Rust.

+5
source

All Articles