vector - 如何从向量中解压(解构)元素?

标签 vector iterator rust

我目前正在做以下事情:

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];

有没有可能做这样的事情?

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

我注意到在一些网站上有各种对矢量解构的引用,但官方文档似乎没有提到它。

最佳答案

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

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

注意 if let 而不是普通的 let。切片模式是可反驳的,因此我们需要考虑到这一点(您可能也希望有一个 else 分支)。

关于vector - 如何从向量中解压(解构)元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32324645/

相关文章:

rust - 如何以函数式方式在向量中查找值并返回其索引?

rust - 为什么在将使用 Diesel 的特征重写为特征方法的函数时得到 "overflow evaluating the requirement"?

c++ - C++ std::binary_search() 和 std::lower_bound() 组合是否意味着我要进行两次二进制搜索?

c++ - std::memcpy 和从 2D vector 复制数据

c++ - 在另一个函数中使用函数内部声明的 vector

java - Java foreach 循环中的 ClassCastException

swift - 如何在 SceneKit 中的 "own"轴上移动旋转的 SCNNode?

rust - 如何让函数返回具有相同项目类型的两个迭代器之一?

c++ - 如何在类中使用重载的 const_iterator?

string - 为什么要添加一个字符串和一个引用,但不能添加两个字符串? (E0308 : Mismatched types)