• rust unwrap


    https://zhuanlan.zhihu.com/p/109242831

    fn main() {
        let path = "/tmp/dat";
        println!("{}", read_file(path));
    }
    
    fn read_file(path: &str) -> String {
        std::fs::read_to_string(path).unwrap()
    }
       Compiling hello_world v0.1.0 (/data2/rust/unwrap)
        Finished dev [unoptimized + debuginfo] target(s) in 0.47s
    [root@bogon unwrap]# cargo run
        Finished dev [unoptimized + debuginfo] target(s) in 0.01s
         Running `target/debug/hello_world`
    thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 2, kind: NotFound, message: "No such file or directory" }', src/main.rs:7:43
    note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
    fn main() {
        let path = "/tmp/dat";  //文件路径
        match read_file(path) { //判断方法结果
            Ok(file) => { println!("{}", file) } //OK 代表读取到文件内容,正确打印文件内容
            Err(e) => { println!("{} {}", path, e) } //Err代表结果不存在,打印错误结果
        }
    }
    
    fn read_file(path: &str) -> Result<String,std::io::Error> { //Result作为结果返回值
        std::fs::read_to_string(path) //读取文件内容
    }
    [root@bogon unwrap2]# cargo run
        Finished dev [unoptimized + debuginfo] target(s) in 0.01s
         Running `target/debug/hello_world`
    /tmp/dat No such file or directory (os error 2)
    [root@bogon unwrap2]# touch /tmp/dat
    [root@bogon unwrap2]# cargo run
        Finished dev [unoptimized + debuginfo] target(s) in 0.01s
         Running `target/debug/hello_world`
    
    [root@bogon unwrap2]# echo 'test unwrap' >> /tmp/dat
    [root@bogon unwrap2]# cargo run
        Finished dev [unoptimized + debuginfo] target(s) in 0.01s
         Running `target/debug/hello_world`
    test unwrap
    
    [root@bogon unwrap2]# 
  • 相关阅读:
    Nginx系列教材 (四)- 和Tomcat进行动静分离整合
    Nginx系列教材 (三)- 反响代理Tomcat
    Nginx系列教材 (二)- 为Nginx准备的多个Tomcat
    Nginx系列教材 (一)- 教程
    Redis系列教材 (六)- Client
    Redis系列教材 (五)- Spring Data Redis 使用例子
    Redis系列教材 (四)- Jedis 教程
    Redis系列教材 (三)- 常见命令
    jq实时监听input值变化
    rem适配的代码
  • 原文地址:https://www.cnblogs.com/dream397/p/14189409.html
Copyright © 2020-2023  润新知