Struct, Enum และ Trait

Rust Methods and impl Blocks

Attach behavior to a struct: methods with &self, changes with &mut self and constructors like new.

  • ระดับกลาง
  • อ่าน 4 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • impl blocks
  • &self and &mut self
  • Associated functions
Receiver → what the method can do
fn area(&self)read
fn scale(&mut self, f)change
fn new(w, h) -> Selfcreate

Functions 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.

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

  1. &self reads the value.
  2. &mut self changes it.
  3. Rectangle::new has no self: it is a constructor.

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

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());
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
area: 12
scaled: 6 x 8 = 48
square: 25

ฝึกฝน

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

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

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

ถัดไป: Enums →

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

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

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