พื้นฐาน 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!.
สิ่งที่คุณจะได้เรียนรู้
- Where a Rust program starts
- Printing with println!
- Why println! ends with !
From source to output
- 1
main.rsYou write the code - 2
rustcThe compiler checks and builds it - 3
main()The program starts in main - 4
Hello, 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.
ประเด็นสำคัญ
- Every program starts in fn main.
- println! is a macro: the ! tells you so.
- rustc compiles the file into a program before it runs.
ตัวอย่าง Rust ที่รันได้
Rust
main.rs
fn main() {
println!("Hello, Rust!");
}
Hello, Rust!ฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- คี่, คู่ หรือไม่ใช่ทั้งสองอย่าง จัดประเภทตัวเลขว่าเป็นจำนวนเต็มคี่ จำนวนเต็มคู่ หรือไม่ใช่ทั้งสองอย่าง ง่าย
- ยกกำลังสองตัวเลข คูณจำนวนเต็มกับตัวมันเอง ง่าย