get system name in rust

To get the system name in Rust, you can use the std::env::var function to get the value of the HOSTNAME environment variable on Linux and Unix systems, or the COMPUTERNAME environment variable on Windows systems. Here is an example:

main.rs
use std::env::var;

fn main() {
    let system_name = match var("HOSTNAME") {
        Ok(val) => val,
        Err(_) => match var("COMPUTERNAME") {
            Ok(val) => val,
            Err(_) => String::from("unknown")
        }
    };

    println!("System name: {}", system_name);
}
288 chars
14 lines

This code first attempts to get the HOSTNAME environment variable using the var function. If that fails (because the variable is not set), it then attempts to get the COMPUTERNAME environment variable using the same function. If both attempts fail, the system name is set to "unknown". Finally, the system name is printed to the console using println!.

gistlibby LogSnag