zoukankan      html  css  js  c++  java
  • 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]# 
  • 相关阅读:
    8月24 杂七杂八
    胡思乱想
    前端思考题
    前端经典面试题
    一些被废弃的东西
    关于设置img图片大小优先级的问题
    关于 removeChild()删除节点
    关于前端基本要求及一些题
    关于 Oracle 11g 先决条件检查失败的解决办法
    《现代前端技术解析》第一章读书笔记(未完成)
  • 原文地址:https://www.cnblogs.com/dream397/p/14189409.html
Copyright © 2011-2022 走看看