Output Macros
Macros สำหรับ output และ debugging เป็นเครื่องมือที่ใช้กันบ่อยที่สุดใน Rust ทั้งสำหรับ user-facing output และ developer debugging โดยแต่ละ macro มีจุดประสงค์และลักษณะการใช้งานที่แตกต่างกัน
1. print! และ println!
Section titled “1. print! และ println!”print! และ println! เป็น macros หลักสำหรับ output ไปยัง stdout โดย println! จะเพิ่ม newline ท้าย ส่วน print! ไม่เพิ่ม
การใช้งานพื้นฐาน
Section titled “การใช้งานพื้นฐาน”macros เหล่านี้รองรับ format strings เหมือน format! รวมถึง named arguments และ positional arguments
fn main() { // Basic printing print!("Hello"); print!(", "); print!("World!"); println!(); // Just newline
// println! adds newline automatically println!("Line 1"); println!("Line 2");
// Empty line println!();
// With formatting let name = "Alice"; let age = 30;
// Positional arguments println!("Name: {}, Age: {}", name, age);
// Named arguments (Rust 2021+) println!("{name} is {age} years old");
// Positional with reuse println!("{0} is {1}, {0} likes {2}", name, age, "Rust");
// Expressions println!("2 + 2 = {}", 2 + 2);}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google