Rust根据不同的操作系统进行条件性编译

Windows与Linux路径分隔符表示是不一样的,在Windows中是\,而在Linux里面是/。在写跨平台代码时,往往会针对不同系统,进行相应的转换。 例如这样一段代码

use std::env::consts::OS;
pub fn convert_path(path_str: &str) -> String{
    let mut result = String::new();
    if OS == "windows" {
        result.push_str(path_str.replace("\\", "/").as_str());
    } else {
        result.push_str(path_str);
    }
    result
}

convert_path方法企图将window系统下\分隔符转换成/,方便统一处理。这段代码并不是条件性编译的,它在运行时进行判断。那么Rust条件性编译怎么做呢?就是用macros cfg。修改后的代码是这样的

pub fn convert_path(path_str: &str) -> String{
    if cfg!(target_os = "windows") {
        String::from(path_str.replace("\\", "/"))
    } else {
        String::from(path_str)
    }
}

好处就是不需要在运行时来判断用户当前处于什么样的操作系统。在编译时就已经做好准备了。

本博客采用 知识共享署名-禁止演绎 4.0 国际许可协议 进行许可

本文标题:Rust根据不同的操作系统进行条件性编译

本文地址:https://jizhong.plus/post/2017/12/rust-conditions-compiled.html