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

It seems what you need is “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);
    }
}

Playground link

Note the if let instead of plain let. Slice patterns are refutable, so we need to take this into account (you may want to have an else branch, too).

Leave a Comment

tech