MST

星途 面试题库

面试题:Rust中Result枚举在文件读取场景下的应用

在Rust中,使用`std::fs::read_to_string`函数读取文件内容时会返回`Result<String, std::io::Error>`类型。请编写一个函数,该函数接收一个文件路径作为参数,使用`read_to_string`读取文件内容。如果读取成功,将内容打印出来;如果失败,打印错误信息。
13.4万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
use std::fs::read_to_string;

fn read_and_print_file(file_path: &str) {
    match read_to_string(file_path) {
        Ok(content) => println!("文件内容: {}", content),
        Err(e) => println!("读取文件时出错: {}", e),
    }
}