דילוג לתוכן המרכזי
eLearner.app
מודול 4 · שיעור 2 מתוך 28/14 בקורס~12 min
שיעורי מודול (2/2)

שיטות ו-impl Blocks

In Rust, methods are similar to functions, but they are defined within the context of a struct (or an enum or trait), and their first parameter is always self, which represents the instance of the struct the method is being called on.

Defining Methods with impl

To define methods on a struct, we use an impl (implementation) block with the struct's name:

Code
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    // This is an instance method. It takes &self for reading.
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

fn main() {
    let rect = Rectangle { width: 30, height: 50 };

    // Call the method using dot notation
    println!("The area is: {}", rect.area());
}

Associated (Static) Functions

Functions defined within an impl block that do not accept self as their first parameter are called associated functions (equivalent to static methods in other languages).

They are often used as constructors to return new instances of the struct. To call them, use the double colon :: syntax:

Code
impl Rectangle {
    // Associated function
    fn square(size: u32) -> Rectangle {
        Rectangle {
            width: size,
            height: size,
        }
    }
}

fn main() {
    // Call the associated function
    let sq = Rectangle::square(10);
}

Methods that Modify State: &mut self

If a method needs to modify the fields of the struct, it must declare its first parameter as &mut self. The instance itself on which the method is called must be declared as mutable (let mut):

Code
impl Rectangle {
    fn double_size(&mut self) {
        self.width *= 2;
        self.height *= 2;
    }
}

Try it yourself

פעילות גופנית#rust.m4.l2.e1
ניסיונות: 0טוען...

Complete the impl block by defining the area method that takes &self and returns u32 (the multiplication of width and height).

טוען עורך...
הצג רמז

Write `fn area(&self) -> u32 { self.width \* self.height }`inside the`impl Rectangle` block.

הפתרון זמין לאחר 3 ניסיונות

פעילות גופנית#rust.m4.l2.e2
ניסיונות: 0טוען...

Define the square associated function inside impl Rectangle, which receives size: u32 and returns a Rectangle instance with width and height equal to size.

טוען עורך...
הצג רמז

Write `fn square(size: u32) -> Rectangle { Rectangle { width: size, height: size } }`inside the`impl` block.

הפתרון זמין לאחר 3 ניסיונות

פעילות גופנית#rust.m4.l2.e3
ניסיונות: 0טוען...

Add the scale mutator method to Rectangle inside the impl block. The scale method must take a mutable reference to self (&mut self) and a factor: u32 parameter, and multiply both the width and height of Rectangle by factor.

טוען עורך...
הצג רמז

Implement `fn scale(&mut self, factor: u32)`to update`self.width`and`self.height`by multiplying them by`factor`.

הפתרון זמין לאחר 3 ניסיונות