如何从向量中解包

如何从向量中解包

本文介绍了如何从向量中解包(解构)元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在执行以下操作:

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'm noticed various references to vector destructuring on some sites but the official docs don't seem to mention it.

推荐答案

看来你需要的是切片模式:

It seems what you need is "slice patterns":

#![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);
    }
}

注意 if let 而不是普通。切片模式是 refutable ,所以我们需要考虑到这一点(你可能想要一个 else 分支)。

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).

这需要每晚版本的Rust。

This will need a nightly version of Rust.

这篇关于如何从向量中解包(解构)元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:04