Struct, enum và trait
Rust Methods and impl Blocks
Attach behavior to a struct: methods with &self, changes with &mut self and constructors like new.
Bạn sẽ học được gì
- impl blocks
- &self and &mut self
- Associated functions
Receiver → what the method can do
fn area(&self)readfn scale(&mut self, f)changefn new(w, h) -> SelfcreateFunctions that belong to a type
An impl block holds the functions that belong to a type. A method takes self as its first parameter and is called with a dot. A function without self, such as new, is called with the type name and ::.
&self borrows the rectangle for reading and &mut self borrows it for changing, which is why rect must be mut to call scale. Self is a short name for the type of the impl block. new and square are associated functions used as constructors.
Những điểm quan trọng
- &self reads the value.
- &mut self changes it.
Rectangle::newhas no self: it is a constructor.
Ví dụ Rust chạy được
Rust
main.rs
struct Rectangle {
width: f64,
height: f64,
}
impl Rectangle {
fn new(width: f64, height: f64) -> Self {
Self { width, height }
}
fn square(size: f64) -> Self {
Self::new(size, size)
}
fn area(&self) -> f64 {
self.width * self.height
}
fn scale(&mut self, factor: f64) {
self.width *= factor;
self.height *= factor;
}
}
fn main() {
let mut rect = Rectangle::new(3.0, 4.0);
println!("area: {}", rect.area());
rect.scale(2.0);
println!("scaled: {} x {} = {}", rect.width, rect.height, rect.area());
println!("square: {}", Rectangle::square(5.0).area());
}
area: 12
scaled: 6 x 8 = 48
square: 25Luyệ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.
- Quy tắc tài khoản ngân hàng Bảo vệ số dư tài khoản bằng các quy tắc nạp và rút tiền, từ chối các thao tác không hợp lệ. Dễ
- Distance Between Points Compute the straight-line distance between two points. Dễ