Answer#
Use the constants in std::env::consts:
use std::env::consts::{ARCH, FAMILY, OS};
fn main() {
println!("OS = {OS}, ARCH = {ARCH}, FAMILY = {FAMILY}");
println!("compiled for Windows: {}", cfg!(windows));
println!("pointer width: {}", cfg!(target_pointer_width = "64"));
}OS = windows, ARCH = x86_64, FAMILY = windows
compiled for Windows: true
pointer width: trueWhat the values are, according to std's documentation: OS is a string such as "windows", "macos" or "linux"; ARCH is such as "x86_64" or "aarch64" (an Apple silicon Mac build reports aarch64); FAMILY is "unix" or "windows".
Important: these are compile-time facts. They say what the executable was built for, not what it runs on:
- A program built for
x86_64and run on an Apple silicon Mac through Apple's translation layer still reportsx86_64. The same applies to emulated x86 programs on Windows on Arm. - They tell you nothing about the version (Windows 10 or 11, macOS 14 or 15). Ask the system for that: use a crate designed for it, or the platform's API, and treat the result as informational.
- A feature test beats a version test. If you need a function that exists from some system version on, try to load it or check for the capability, rather than comparing version numbers.
Use consts::OS for log lines, bug-report text ("running on ...") and choosing a download file name. Use #[cfg] when different code must be compiled in (see the cfg threads).
Common mistakes#
- Using
OSto decide path separators. UsePathandPathBuf. - Using string comparison on
OSwhere an enum would be better:match OS { "windows" => ..., "macos" => ..., _ => ... }needs a fallback arm for other values.
Related questions#
How do I build for both Intel and Apple silicon Macs?#
That is a packaging question: build once per CPU target and combine; see the macOS packaging threads.
Sources#
- std::env::consts: https://doc.rust-lang.org/std/env/consts/index.html (read 2026-12-05)