Rust 如何将文本文件中的行读入i32s元组向量?
这是我的尝试:Rust 如何将文本文件中的行读入i32s元组向量?,rust,Rust,这是我的尝试: use std::fs; fn main() { //let input = fs::read_to_string("input.txt").unwrap(); let input = "1, 2\n3, 4\n5, 6"; let lines: Vec<String> = input.split("\n").map(|s| s.to_string()).collect();
use std::fs;
fn main() {
//let input = fs::read_to_string("input.txt").unwrap();
let input = "1, 2\n3, 4\n5, 6";
let lines: Vec<String> = input.split("\n").map(|s| s.to_string()).collect();
let data: Vec<(i32, i32)> = lines
.iter()
.map(|x| {
x.split(',')
.map(|y| y.trim().parse::<i32>().unwrap())
.collect()
.unwrap()
})
.collect();
println!("{:?}", data);
}
使用std::fs;
fn main(){
//让input=fs::读取到字符串(“input.txt”).unwrap();
让输入=“1,2\n3,4\n5,6”;
let line:Vec=input.split(“\n”).map(|s|s.to_string()).collect();
let data:Vec=行
.国际热核实验堆(iter)
.map(|x|){
x、 拆分(',')
.map(| y | y.trim().parse::().unwrap())
.collect()
.unwrap()
})
.收集();
println!(“{:?}”,数据);
}
我得到一个错误:
错误[E0282]:需要类型注释
-->src/main.rs:13:18
|
13 |收集()
|^^^^无法推断关联函数“collect”上声明的类型参数“B”的类型`
|
=注意:此时必须知道类型
帮助:考虑在方法调用中指定类型参数
|
13.收集::()
| ^^^^^
不能使用将数据收集到元组中。collect
。一种选择是使用需要itertools
板条箱的:
使用itertools::itertools;
fn main(){
让输入=“1,2\n3,4\n5,6”;
let line:Vec=input.split(“\n”).map(|s|s.to_string()).collect();
let data:Vec=行
.国际热核实验堆(iter)
.map(|x|){
x、 拆分(',')
.map(| y | y.trim().parse::().unwrap())
.collect_tuple()
.unwrap()
})
.收集();
println!(“{:?}”,数据);
}
D'oh,我完全没有想到
collect
会试图创建一个集合而不是元组。谢谢这是把这个字符串变成一个元组向量的最好方法吗?还是我错过了一个更简单的方法?@ TunBuffED53。如果你认为没有一个依赖项是“更简单”的,那么你可以“Ivnc我猜我在寻找更少冗长的,但是我知道你会如何做到这一点。谢谢