【问题标题】:Error: no method named `parse` found for enum `Result` in the current scope错误:在当前范围内没有为枚举 `Result` 找到名为 `parse` 的方法
【发布时间】:2021-12-02 07:26:30
【问题描述】:

我正在尝试读取带有 1234 823 之类数字的 txt 文件,我想将它们转换为 u16.collect() 将它们转换为 vec。它给了我这个错误:no method named "parse" found for enum "Result" in the current scope。那么我该如何解决呢?

let file_in = fs::File::open("input.txt").unwrap(); 
let file_reader = BufReader::new(file_in); 
let vec: Vec<u16> = file_reader.lines().map(|x| x.parse::<u16>().unwrap()).collect();

【问题讨论】:

    标签: file parsing vector rust integer


    【解决方案1】:

    产生instances of io::Result&lt;String&gt;lines returns an iterator。所以你可以unwrap instance得到包含的Ok value

    let vec: Vec<u16> = file_reader
        .lines()
        .map(|x| x.unwrap().parse::<u16>().unwrap())
        .collect();
    

    但是,如果任何一行未能解析(到u16),这将导致恐慌。所以你可以使用filter_map instead.

    let vec: Vec<u16> = file_reader
        .lines()
        .filter_map(|x| x.unwrap().parse::<u16>().ok())
        .collect();
    

    【讨论】:

    • ...如果读取该行时出错,这将导致恐慌。您可以改用.filter_map(|x| x.ok()?.parse::&lt;u16&gt;().ok())
    • parse()lines() 中的错误使用filter_map() 将导致错误被静默删除。通常最佳实践是在第一个错误时停止,例如通过收集到Result。这里有点复杂,因为parse()lines() 返回的错误是不同的,所以它需要一些粘合,如shown here。如果 OP 正在做 AOC 练习,unwrap() 可能会做。
    猜你喜欢
    • 2018-07-08
    • 2019-11-16
    • 2021-05-13
    • 2017-03-22
    • 2023-01-15
    • 2017-03-16
    • 2021-02-28
    • 2021-02-19
    • 2015-02-23
    相关资源
    最近更新 更多