Rust cơ bản
Rust Functions and Return Values
Define functions with typed parameters and return a value without writing return.
Bạn sẽ học được gì
- Parameters with types
- Return type after ->
- The last expression is returned
area(4, 5)
- 1
4, 5arguments - 2
width * heightthe body runs - 3
20returned to the caller
Values go in, one value comes out
A function groups code under a name. In Rust you write the type of every parameter and, after ->, the type of the value the function returns.
The last expression of a function is its return value when it has no semicolon, so width * height is returned without the return keyword. format! builds a String the same way println! prints one.
Những điểm quan trọng
- Every parameter needs a type.
- -> u32 says what the function returns.
- A final expression without ; is the return value.
Ví dụ Rust chạy được
Rust
main.rs
fn area(width: u32, height: u32) -> u32 {
width * height
}
fn describe(name: &str, size: u32) -> String {
format!("{name} covers {size} square meters")
}
fn main() {
let size = area(4, 5);
println!("{}", describe("The room", size));
}
The room covers 20 square metersLuyệ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ớn Nhất Trong Ba Số Chọn số lớn nhất trong ba số mà không dùng hàm max có sẵn. Dễ
- Celsius to Fahrenheit Convert a temperature from Celsius to Fahrenheit. Dễ