Env Structs
Structs และ types สำหรับ environment operations ใน Rust รวมถึง command line arguments, environment variables และ current directory - พื้นฐานที่สำคัญสำหรับการเขียน CLI applications และ cross-platform programs
Args และ ArgsOs
Section titled “Args และ ArgsOs”Iterators สำหรับ command line arguments โดย Args ให้ String (UTF-8) ส่วน ArgsOs ให้ OsString ที่อาจไม่เป็น valid UTF-8 - สิ่งสำคัญคือต้องเข้าใจว่าบน Unix/Linux file paths อาจมี bytes ที่ไม่ใช่ valid UTF-8 ได้
Parameters ของ Iterator Methods
Section titled “Parameters ของ Iterator Methods”| Method | Parameters | Returns | Description |
|---|---|---|---|
env::args() | - | Args | Iterator ของ String (panics ถ้าไม่ใช่ UTF-8) |
env::args_os() | - | ArgsOs | Iterator ของ OsString (safe สำหรับทุก input) |
.enumerate() | - | Enumerate<Args> | เพิ่ม index กับแต่ละ item |
.skip(n) | n: usize | Skip<Args> | ข้าม n items แรก |
.nth(n) | n: usize | Option<String> | เอา item ที่ index n |
.collect() | - | Vec<T> | เก็บทั้งหมดลง collection |
Command Line Arguments
Section titled “Command Line Arguments”use std::env;
fn main() { // Args - iterator over String (UTF-8) // ตัว argument แรกคือชื่อ program เสมอ println!("=== Args (UTF-8) ==="); for (i, arg) in env::args().enumerate() { println!(" [{}] {}", i, arg); }
// ArgsOs - iterator over OsString (may not be UTF-8) // ใช้เมื่อต้อง handle file paths ที่อาจมี invalid UTF-8 println!("\n=== ArgsOs ==="); for (i, arg) in env::args_os().enumerate() { println!(" [{}] {:?}", i, arg); }
// Collect to Vec - วิธีที่นิยมใช้กัน let args: Vec<String> = env::args().collect(); println!("\nCollected: {:?}", args);
// Skip program name - args ที่ user ใส่มาจริงๆ let user_args: Vec<String> = env::args().skip(1).collect(); println!("User args: {:?}", user_args);
// Get specific argument safely if let Some(first) = env::args().nth(1) { println!("First user arg: {}", first); } else { println!("No arguments provided"); }
// Check argument count let argc = env::args().count(); println!("\nTotal arguments: {} (including program name)", argc);}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google