ข้ามไปยังเนื้อหา

Hello, World — โปรแกรม Rust แรกของคุณ

การเขียน “Hello, world!” คือพิธีกรรมแรกในทุกภาษาใหม่ ใน TypeScript คุณใช้ console.log ส่วนใน Rust ใช้ println! สองตัวนี้หน้าตาคล้ายกัน แต่เบื้องหลังทำงานต่างกันมาก

TypeScript
// TypeScript hello world
const greeting: string = "Hello, world!";
console.log(greeting);
// Template literals
const name = "TypeScript developer";
console.log(`Welcome, ${name}!`);
Rust
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 ไม่ใช่ Runtime
  • let greeting: &str&str คือ String slice หรือ Reference ไปยังลำดับ UTF-8 bytes มองว่าเป็น Immutable view ของ string ก็ได้ ส่วน string type ที่ Owned และอยู่บน Heap คือ String
  • Semicolons — Rust ใช้ Semicolons เพื่อจบ Statements เหมือนกับ TypeScript

println! มีความสามารถมากกว่า console.log Format string ใช้ {} เป็น Placeholder และคุณสามารถอ้างอิงตัวแปรด้วยชื่อ ({name}) หรือใช้ Positional placeholders:

println!("{}", value); // positional
println!("{value}"); // named (Rust 1.58+)
println!("{:?}", value); // debug format — works on most types
println!("{:#?}", value); // pretty debug format
println!("{:.2}", 3.14159); // 3.14 — two decimal places

หลังจาก Scaffold ด้วย cargo new hello-world ไฟล์ src/main.rs จะมี:

fn main() {
println!("Hello, world!");
}

สั่งรันด้วย:

Terminal window
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}");
}
เครื่องหมาย `!` หลัง `println` บ่งบอกอะไร?
Function Entry point ใน Rust binary program คืออะไร?
Format specifier ใดที่ Print ค่าโดยใช้ Debug formatting ใน println!?
คำสั่งใด Compile และรัน Rust project ทันที?