如何从向量创建元组? [英] How to create a tuple from a vector?

查看:46
本文介绍了如何从向量创建元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个拆分字符串并解析每个项目的示例,将其放入一个在编译时已知大小的元组中.

Here's an example that splits a string and parses each item, putting it into a tuple whose size is known at compile time.

use std::str::FromStr;

fn main() {
    let some_str = "123,321,312";
    let num_pair_str = some_str.split(',').collect::<Vec<&str>>();
    if num_pair_str.len() == 3 {
        let num_pair: (i32, i32, i32) = (
            i32::from_str(num_pair_str[0]).expect("failed to parse number"),
            i32::from_str(num_pair_str[1]).expect("failed to parse number"),
            i32::from_str(num_pair_str[2]).expect("failed to parse number"),
        );
        println!("Tuple {:?}", num_pair);
    }
}

有没有办法避免重复解析数字?

Is there a way to avoid repetition parsing the numbers?

这是一个如果 Rust 支持类似 Python 的推导式的示例:

This is an example of what it might look like if Rust supported Python-like comprehensions:

let num_pair: (i32, i32, i32) = (
    i32::from_str(num_pair_str[i]).expect("failed to parse number")
    for i in 0..3
);

是否可以以扩展向量的方式声明元组?

Is it possible to declare the tuple in a way that expands the vector?

推荐答案

您不能使用类似 Python 的列表推导式,因为 Rust 没有它.最接近的是通过另一个迭代器显式地完成它.您不能直接收集到元组中,因此您需要另一个显式步骤来转换向量:

You can't use Python-like list comprehension, as Rust doesn't have it. The closest thing is to do it explicitly via another iterator. You can't directly collect into a tuple, so you need another explicit step to convert the vector:

use std::str::FromStr;

fn main() {
    let some_str = "123,321,312";
    let num_pair_str = some_str.split(',').collect::<Vec<_>>();
    if num_pair_str.len() == 3 {
        let v = num_pair_str.iter().map(|s| i32::from_str(s).expect("failed to parse number"))
            .collect::<Vec<_>>();
        let num_pair: (i32, i32, i32) = (v[0], v[1], v[2]);
        println!("Tuple {:?}", num_pair);
    }
}

如果您想避免中间向量,您可以执行以下操作:

If you want to avoid the intermediate vectors you can do something like the following:

use std::str::FromStr;

fn main() {
    let some_str = "123,321,312";
    let it0 = some_str.split(',');
    if it0.clone().count() == 3 {
        let mut it = it0.map(|s| i32::from_str(s).expect("failed to parse number"));
        let num_pair: (i32, i32, i32) =
            (it.next().unwrap(), it.next().unwrap(), it.next().unwrap());
        println!("Tuple {:?}", num_pair);
    }
}

这篇关于如何从向量创建元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆