如何以功能方式将字符串向量转换为整数向量? [英] How do I convert a vector of strings to a vector of integers in a functional way?

查看:93
本文介绍了如何以功能方式将字符串向量转换为整数向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Vec<&str>转换为Vec<u16>,但我不知道实现此功能的方法.

I'm trying to convert Vec<&str> to Vec<u16> but I can't figure out a functional way to do it.

let foo: &str = "1,2,3"; // Parsing a string here
let bar: Vec<&str> = foo.split(",").collect(); // Bar is a nice vector of &str's

我需要将bar放入Vec<u16>.

推荐答案

有一个迭代器适配器 map !您将像这样使用它:

There's an iterator adapter map! You'd use it like this:

let bar: Vec<u16> = foo.split(",").map(|x| x.parse::<u16>().unwrap()).collect();

parse 是一种库函数依靠特征 FromStr ,它可以返回错误,因此我们需要unwrap()错误类型. (对于一个简短的示例,这是个好主意,但是在实际代码中,您将希望正确处理该错误-如果该值不存在u16,则程序将崩溃.)

parse is a library function that relies on the trait FromStr, and it can return an error, so we need to unwrap() the error type. (This is a good idea for a short example, but in real code, you will want to handle the error properly - if you have a value that's not a u16 there, your program will just crash).

map接受一个闭包,该闭包按值获取它的参数,然后返回 lazily 应用该函数获得的迭代器.您正在 collect 全部其中的值,但如果您仅 take(5) ,您只需解析其中的5个字符串.

map takes a closure that takes it's parameter by value and then returns the iterator obtained by lazily applying that function. You're collecting all of the values here, but if you only take(5) of them, you would only parse 5 of the strings.

这篇关于如何以功能方式将字符串向量转换为整数向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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