Environment - ตัวแปรระบบ
std::env module สำหรับอ่านและจัดการ environment variables, command line arguments และข้อมูลระบบต่างๆ ใน Rust
env มีอะไร?
Section titled “env มีอะไร?”Module นี้ให้ access ถึงข้อมูลสำคัญของ runtime environment:
- Environment variables - ตัวแปร
HOME,PATH,RUST_LOGฯลฯ - Command line arguments - ข้อมูลที่ส่งมาตอนรันโปรแกรม
- Current directory - working directory ปัจจุบัน
- System info - OS, architecture และ platform constants
1. Environment Variables
Section titled “1. Environment Variables”อ่าน Variables
Section titled “อ่าน Variables”use std::env;
fn main() { // ============================================ // var() - return Result<String, VarError> // ============================================
match env::var("HOME") { Ok(home) => println!("HOME: {}", home), Err(e) => println!("HOME not set: {}", e), }
// ============================================ // var_os() - return Option<OsString> // ============================================
// ใช้กับ values ที่อาจไม่ใช่ valid UTF-8 if let Some(path) = env::var_os("PATH") { println!("PATH exists (length: {} chars)", path.to_string_lossy().len()); }
// ============================================ // Check existence // ============================================
let has_home = env::var("HOME").is_ok(); let has_debug = env::var("DEBUG").is_ok();
println!("\nhas HOME: {}", has_home); println!("has DEBUG: {}", has_debug);
// ============================================ // With default value // ============================================
let editor = env::var("EDITOR").unwrap_or("vim".to_string()); let shell = env::var("SHELL").unwrap_or("/bin/sh".to_string());
println!("\nEDITOR: {}", editor); println!("SHELL: {}", shell);
// ============================================ // Common patterns // ============================================
// Check for feature flag let debug_mode = env::var("DEBUG").is_ok(); if debug_mode { println!("Debug mode enabled"); }
// Parse as number let port: u16 = env::var("PORT") .ok() .and_then(|p| p.parse().ok()) .unwrap_or(8080);
println!("PORT: {}", port);}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google