← 中文资源

简体中文版本

env::consts 获取目标平台常量

从 env::consts 读取 OS、ARCH、FAMILY 与可执行文件后缀,安装路径和二进制命名随目标平台自动对齐,无需运行时探测。

阅读英文原文

实现说明

env::consts 获取目标平台常量可以归结为函数 main。

使用要点

  • 直接运行文件,输出会带上标签,比如 os:、arch:、family:——输出的每一行都能指回产生它的那次调用。

常见问题

运行「env::consts 获取目标平台常量」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 os:、arch:、family: 标签标明各步骤。

核心语句

let separator = if FAMILY == "windows" { '\\' } else { '/' };

代码示例

use std::env::consts::{ARCH, DLL_SUFFIX, EXE_SUFFIX, FAMILY, OS};

fn main() {
    // compile-time constants: the toolchain bakes in the target platform
    println!("os: {OS}");
    println!("arch: {ARCH}");
    println!("family: {FAMILY}");

    // suffixes decide binary names: main vs main.exe, libfoo vs foo.dll
    println!("exe suffix: '{EXE_SUFFIX}'");
    println!("dll suffix: '{DLL_SUFFIX}'");

    // runtime branch keyed on the platform family
    let separator = if FAMILY == "windows" { '\\' } else { '/' };
    println!("path separator: {separator}");
}