Skip to content
เข้าสู่ระบบ

Environment Functions

การจัดการ environment variables และ process information เป็นส่วนสำคัญของ system programming ใน Rust โดย std::env module ให้เครื่องมือครบครันสำหรับอ่าน เขียน และจัดการ environment ของ process

หัวข้อหลัก: Environment Variables

Section titled “หัวข้อหลัก: Environment Variables”

Environment variables เป็นวิธีมาตรฐานในการ configure applications โดยไม่ต้องเปลี่ยน code เหมาะสำหรับ secrets, configuration และ runtime settings

การอ่าน Environment Variables

Section titled “การอ่าน Environment Variables”

Rust มี 2 functions หลักคือ var() ที่ return String และ var_os() ที่ return OsString โดย var() จะ fail ถ้าค่าไม่ใช่ valid UTF-8

use std::env;
fn main() {
// var() - get as String
println!("=== env::var() ===");
match env::var("HOME") {
Ok(val) => println!("HOME = {}", val),
Err(e) => println!("HOME not set: {}", e),
}
// var_os() - get as OsString (faster, no UTF-8 check)
println!("\n=== env::var_os() ===");
if let Some(path) = env::var_os("PATH") {
println!("PATH length: {} bytes", path.len());
}
// Difference
println!("\n=== var vs var_os ===");
println!("var(): Returns Result<String, VarError>");
println!("var_os(): Returns Option<OsString>");
println!();
println!("Use var_os() when:");
println!(" - Performance matters");
println!(" - Value might not be valid UTF-8");
println!(" - Only need to pass to other OS calls");
}

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด