gpt4 book ai didi

rust - 将结果的错误代码转换为字符串

转载 作者:行者123 更新时间:2023-12-05 01:18:08 26 4
gpt4 key购买 nike

我想打开一个文件,但是在我的程序无法打开它的情况下,我想向用户打印一条错误消息并提早退出。

use std::fs::File;

fn main() {
let file = "something.txt";
let file = match File::open(file) {
Ok(val) => val,
Err(e) => {
//err_string is not a real function, what would you use?
println!("failed to open file: {}", e.err_string());
return;
}
};
}

最佳答案

向用户显示错误消息并提早退出:
1.您可以使用File::open("something.txt")?,尝试以下示例(无需 panic ,仅显示错误消息):


use std::fs::File;
use std::io::prelude::*;

fn main() -> std::io::Result<()> {
let mut file = File::open("something.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
assert_eq!(contents, "Hello, world!");
Ok(())
}

输出(错误时):
Error: Os { code: 2, kind: NotFound, message: "No such file or directory" }

  • 使用.expect("msg"): panic (如果值是Err),并带有包括所传递消息的 panic 消息和Err的内容(开发人员友好的,因为显示了文件名和行号):
  • use std::fs::File;
    use std::io::prelude::*;

    fn main() {
    let mut file = File::open("something.txt").expect("failed to open file");
    let mut contents = String::new();
    file.read_to_string(&mut contents)
    .expect("failed to read file");
    assert_eq!(contents, "Hello, world!");
    }

    输出(错误时):
    thread 'main' panicked at 'failed to open file: 
    Os { code: 2, kind: NotFound, message: "No such file or directory" }',
    src/main.rs:17:20
    note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

  • 无需 panic ,只显示一条错误消息:
  • use std::fs::File;
    use std::io::prelude::*;

    fn main() {
    let mut file = match File::open("something.txt") {
    Ok(val) => val,
    Err(e) => {
    println!("failed to open file: {}", e);
    return;
    }
    };

    let mut contents = String::new();
    file.read_to_string(&mut contents)
    .expect("failed to read file");
    assert_eq!(contents, "Hello, world!");
    }

    输出(错误时):
    failed to open file: No such file or directory (os error 2)

    关于rust - 将结果的错误代码转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60145407/

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