本文介绍了如何使用函数式将字符串解析为浮点列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我试图将一个字符串解析为Rust中的浮点值列表。我会假设有一个聪明的方法来使用迭代器和 Option s;不过,我无法忽略由parse()调用失败导致的 Err 值。 Rust教程似乎没有包含任何这样的例子,并且文档充其量也是令人困惑的。 我将如何使用功能样式向量来实现它/列表操作? 功能性风格 遇到 Err input.split().map(| s | s.parse ::< f32>()。unwrap())。collect ::< Vec<>>() 迭代式 按照预期浮动值 fn parse_string(输入:& str) - > VEC< F32> { let mut vals = Vec :: new(); for input.split_whitespace(){ match val.parse(){ Ok(v)=> vals.push(v), Err(_)=> (),} } vals } fn main(){ let params = parse_string(1 -5.2 3.8 ABC); for& param in params.iter(){ println!({:. 2},param); } } 解决方案 filter_map 做你想做的事,转换值并过滤掉 None s: input.split().filter_map(| s | s.parse ::< f32>()。ok())。collect ::< Vec<>>(); 请注意 ok 方法将结果到期权。 I am trying to parse a string into a list of floating-point values in Rust. I would assume there is a clever way to do this using iterators and Options; however, I cannot get it to ignore the Err values that result from failed parse() calls. The Rust tutorial doesn't seem to cover any examples like this, and the documentation is confusing at best.How would I go about implementing this using the functional-style vector/list operations? Pointers on better Rust style for my iterative implementation would be appreciated as well!"Functional"-stylePanics when it encounters an Errinput.split(" ").map(|s| s.parse::<f32>().unwrap()).collect::<Vec<_>>()Iterative-styleIgnores non-float values as intendedfn parse_string(input: &str) -> Vec<f32> { let mut vals = Vec::new(); for val in input.split_whitespace() { match val.parse() { Ok(v) => vals.push(v), Err(_) => (), } } vals}fn main() { let params = parse_string("1 -5.2 3.8 abc"); for &param in params.iter() { println!("{:.2}", param); }} 解决方案 filter_map does what you want, transforming the values and filtering out Nones:input.split(" ").filter_map(|s| s.parse::<f32>().ok()).collect::<Vec<_>>();Note the ok method to convert the Result to an Option. 这篇关于如何使用函数式将字符串解析为浮点列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-28 09:48