MST

星途 面试题库

面试题:Rust中Result枚举链式调用基础

请编写一段Rust代码,使用Result枚举的链式调用,实现从文件中读取一行内容并将其解析为整数。若读取失败或解析失败,返回对应的错误信息。
21.3万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
use std::fs::File;
use std::io::{self, BufRead, BufReader};

fn read_line_as_int() -> Result<i32, io::Error> {
    let file = File::open("your_file.txt")?;
    let reader = BufReader::new(file);
    let line = reader.lines().next().transpose()?;
    line.parse::<i32>().map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Failed to parse as integer"))
}