• Rust引用转换时避免使用变量


    本文较短,留待日后参考。

    检测文件存在引发的问题

    笔者在使用Rust编写某特定功能时,需要通过命令行转入的参数检测某文件是否存在;为方便说明问题,笔者编写的代码精简如下:

    use std::path::Path;
    
    fn main() {
        let args = std::env::args_os().skip(1);
        for file in args {
            let filepath: &Path = file.as_ref();
            let exist = filepath.exists();
            let filestr = file.as_os_str().to_string_lossy();
            println!("File '{}' exists: {}", filestr, exist);
            // if exist {
            //    process_file(&filestr);
            // }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    编译后执行的结果如下:

    $ cargo run --release /usr/bin/bash /usr/bin/zsh
        Finished release [optimized] target(s) in 0.01s
         Running `target/release/file-check /usr/bin/bash /usr/bin/zsh`
    File '/usr/bin/bash' exists: true
    File '/usr/bin/zsh' exists: false
    
    • 1
    • 2
    • 3
    • 4
    • 5

    笔者的诸求比较简单,因filepath引用变量的类型为&Path,且仅使用到一次(调用了其exists方法),笔者希望代码更为简洁,省去这一转换的引用变量;换句话说,删除仅用一次的filepath引用变量。

    引用转换时指定转换类型

    以上代码中,for循环遍历迭代变量args得到的file类型为OsString,该类型有两种引用转换:

    impl AsRef<OsStr> for OsString
    fn as_ref(&self) -> &OsStr
    
    impl AsRef<Path> for OsString
    fn as_ref(&self) -> &Path
    
    • 1
    • 2
    • 3
    • 4
    • 5

    这两种转换分别可以得到&OsStr&Path两种类型的引用。为了避免引入仅用一次的filepath,笔者修改后的代码如下:

    use std::path::Path;
    
    fn main() {
        let args = std::env::args_os().skip(1);
        for file in args {
            let exist = AsRef::<Path>::as_ref(&file).exists();
            let filestr = file.as_os_str().to_string_lossy();
            println!("File '{}' exists: {}", filestr, exist);
            // if exist {
            //    process_file(&filestr);
            // }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    代码用,笔者用到了显示指定引用转变类型的方法得到了一个&Path的引用:

    AsRef::<Path>::as_ref(&file)
    
    • 1

    随后立即调用其exists()方法,从而直接得到文件是否存在的布尔值,省略了filepath引用变量。尽管这是一个小的改进,但积累起来可以让开发者编写更加简洁高效的代码;此外,这一改进亦可见Rust语法的灵活性。

  • 相关阅读:
    【数据结构】基础:栈(C语言)
    【图像分割】实战篇(1)传统图像分割
    P11机器学习--李宏毅笔记(Transformer Decoder)Testing部分
    C++单例模式
    spring 微服务nacos未授权访问漏洞修复
    面试后的反思与总结:不断进步的关键
    K-最近邻算法
    Windows系统上安装MySQL 5.7详细步骤
    linux系统编程之二
    深入学习JVM底层(五):类加载机制
  • 原文地址:https://blog.csdn.net/yeholmes/article/details/127950799