Env Enums
Environment-related enums
หัวข้อหลัก: VarError Enum
Section titled “หัวข้อหลัก: VarError Enum”VarError ใช้สำหรับ error จากการอ่าน environment variables
Variants และการใช้งาน
Section titled “Variants และการใช้งาน”use std::env::{self, VarError};
fn main() { println!("=== VarError Variants ===\n");
// NotPresent - variable doesn't exist match env::var("DEFINITELY_NOT_SET_XYZ") { Err(VarError::NotPresent) => { println!("NotPresent: Variable not found"); } _ => unreachable!(), }
// NotUnicode - value isn't valid UTF-8 println!("\nNotUnicode: Value contains invalid UTF-8");
// Match on VarError fn get_config(key: &str) -> Result<String, String> { env::var(key).map_err(|e| { match e { VarError::NotPresent => { format!("{} is not set", key) } VarError::NotUnicode(os_str) => { format!("{} contains invalid UTF-8: {:?}", key, os_str) } } }) }
println!("\n=== Error Messages ==="); match get_config("HOME") { Ok(val) => println!("HOME: {}", val), Err(e) => println!("Error: {}", e), }
match get_config("NOT_FOUND") { Ok(val) => println!("Value: {}", val), Err(e) => println!("Error: {}", e), }}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google