พื้นฐาน Rust

Hello World in Rust: Structure of a Program

Write your first Rust program and see what each part does: fn main, the braces and println!.

  • ระดับเริ่มต้น
  • อ่าน 2 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • Where a Rust program starts
  • Printing with println!
  • Why println! ends with !
From source to output
  1. 1main.rsYou write the code
  2. 2rustcThe compiler checks and builds it
  3. 3main()The program starts in main
  4. 4Hello, Rust!The text appears

How a Rust program runs

Every Rust program starts in a function called main. The println! macro prints a line of text; the exclamation mark shows that it is a macro, not an ordinary function.

fn declares a function and the braces hold its body. Each statement ends with a semicolon. The compiler turns the file into a program, then the program runs main and prints the text.

ประเด็นสำคัญ

  1. Every program starts in fn main.
  2. println! is a macro: the ! tells you so.
  3. rustc compiles the file into a program before it runs.

ตัวอย่าง Rust ที่รันได้

Rust
รันโค้ด →
main.rs
fn main() {
    println!("Hello, Rust!");
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
Hello, Rust!

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ถัดไป: Variables and Mutability →

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด