gpt4 book ai didi

rust - 您如何将文本文件中的行读入i32s元组的向量中?

转载 作者:行者123 更新时间:2023-12-03 11:36:30 25 4
gpt4 key购买 nike

这是我的尝试:

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);
}
我得到了错误:
error[E0282]: type annotations needed
--> src/main.rs:13:18
|
13 | .collect()
| ^^^^^^^ cannot infer type for type parameter `B` declared on the associated function `collect`
|
= note: type must be known at this point
help: consider specifying the type argument in the method call
|
13 | .collect::<B>()
| ^^^^^

最佳答案

您无法使用.collect收集到一个元组中。一种选择是使用 Itertools::collect_tuple ,这需要itertools crate :

use itertools::Itertools;

fn main() {
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_tuple()
.unwrap()
})
.collect();

println!("{:?}", data);
}
Playground link

关于rust - 您如何将文本文件中的行读入i32s元组的向量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65599568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com