• 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]# 
  • 相关阅读:
    delphi RTTI 反射技术
    delphi 自我删除和线程池(1000行代码,需要仔细研究)
    寻找两个已序数组中的第k大元素
    OpenCV中的神器Image Watch
    PYTHON 之 【RE模块的正则表达式学习】
    Call U
    微软IE11浏览器的7大变化
    集群应用及运维经验小结
    逆序对:从插入排序到归并排序
    Jquery 图片轮播实现原理总结
  • 原文地址:https://www.cnblogs.com/dream397/p/14189409.html
Copyright © 2020-2023  润新知