Hello, World — โปรแกรม Rust แรกของคุณ
โปรแกรมที่ทุกภาษาเริ่มต้น
หัวข้อที่มีชื่อว่า “โปรแกรมที่ทุกภาษาเริ่มต้น”การเขียน “Hello, world!” คือพิธีกรรมแรกในทุกภาษาใหม่ ใน TypeScript คุณใช้ console.log ส่วนใน Rust ใช้ println! สองตัวนี้หน้าตาคล้ายกัน แต่เบื้องหลังทำงานต่างกันมาก
เปรียบเทียบแบบเคียงข้างกัน
หัวข้อที่มีชื่อว่า “เปรียบเทียบแบบเคียงข้างกัน”// TypeScript hello worldconst greeting: string = "Hello, world!";console.log(greeting);
// Template literalsconst name = "TypeScript developer";console.log(`Welcome, ${name}!`);fn main() { let greeting: &str = "Hello, world!"; println!("{greeting}");
// Named argument in format string let name = "TypeScript developer"; println!("Welcome, {name}!");}มีหลายสิ่งที่ควรสังเกตทันที:
fn main()— ทุก Rust binary เริ่มต้นที่นี่ ไม่มี Module system หรือ Top-level execution แบบ Node.js;mainคือ Entry point ที่จำเป็นprintln!— เครื่องหมายอัศเจรีย์บอกว่านี่คือ Macro ไม่ใช่ Function ตัว Compiler จะตรวจ Format string ตั้งแต่ Compile time แล้วแทน{greeting}ด้วยค่าของตัวแปรgreetingคล้ายกับ Template literal แต่ตรวจตั้งแต่ Compile time ไม่ใช่ Runtimelet greeting: &str—&strคือ String slice หรือ Reference ไปยังลำดับ UTF-8 bytes มองว่าเป็น Immutable view ของ string ก็ได้ ส่วน string type ที่ Owned และอยู่บน Heap คือString- Semicolons — Rust ใช้ Semicolons เพื่อจบ Statements เหมือนกับ TypeScript
การจัดรูปแบบด้วย println!
หัวข้อที่มีชื่อว่า “การจัดรูปแบบด้วย println!”println! มีความสามารถมากกว่า console.log Format string ใช้ {} เป็น Placeholder และคุณสามารถอ้างอิงตัวแปรด้วยชื่อ ({name}) หรือใช้ Positional placeholders:
println!("{}", value); // positionalprintln!("{value}"); // named (Rust 1.58+)println!("{:?}", value); // debug format — works on most typesprintln!("{:#?}", value); // pretty debug formatprintln!("{:.2}", 3.14159); // 3.14 — two decimal placesการรันโปรแกรม
หัวข้อที่มีชื่อว่า “การรันโปรแกรม”หลังจาก Scaffold ด้วย cargo new hello-world ไฟล์ src/main.rs จะมี:
fn main() { println!("Hello, world!");}สั่งรันด้วย:
cargo runคุณจะเห็น:
Compiling hello-world v0.1.0 Finished dev [unoptimized + debuginfo] target(s) in 0.42s Running `target/debug/hello-world`Hello, world!การรันครั้งแรก Compile; การรันครั้งถัดไปจะ Compile เฉพาะไฟล์ที่เปลี่ยนแปลง — คล้ายกับการ Compile TypeScript แบบ Incremental
ลองทดสอบ
หัวข้อที่มีชื่อว่า “ลองทดสอบ”รันโปรแกรม Rust ในเบราว์เซอร์ของคุณตอนนี้เลย ไม่ต้องติดตั้งอะไร
fn main() { println!("Hello, world!");
let name = "TypeScript developer"; println!("Welcome, {name}!");
// Debug formatting with {:?} let numbers = [1, 2, 3, 4, 5]; println!("numbers = {numbers:?}");
// Formatted floats let pi = 3.14159; println!("pi = {pi:.2}");}Compiling…