Rust cơ bản
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!.
Bạn sẽ học được gì
- 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.
Những điểm quan trọng
- Every program starts in fn main.
- println! is a macro: the ! tells you so.
- rustc compiles the file into a program before it runs.
Ví dụ Rust chạy được
Rust
main.rs
fn main() {
println!("Hello, Rust!");
}
Hello, Rust!Luyện tập
Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.
Bạn học xong bài này chưa?
Đánh dấu đã học để theo dõi tiến độ của bạn.
Tiến độ của bạn đang được lưu trong trình duyệt này Đăng nhập để giữ tiến độ trên mọi thiết bị.
Luyện tập với thử thách
Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.
- Số lẻ, số chẵn, hoặc không phải Phân loại một số là số nguyên lẻ, số nguyên chẵn, hoặc không phải cả hai. Dễ
- Bình phương một số Nhân một số nguyên với chính nó. Dễ