Start learning free

LESSON 187 OF 348 · OBJECT-ORIENTED PROGRAMMING

Member Functions in Rust in Rust

Lesson

TL ; DR:

  • A member function (or method) is a function declared inside a class. It can read and write the object's data members.


  • Define member functions in an impl block so they can be called from outside:

    struct Dog {
        pub name: String,
    }
    
    impl Dog {
        fn new(name: &str) -> Dog {
            Dog { name: name.to_string() }
        }
    
        pub fn bark(&self) {
            println!("Woof! I am {}", self.name);
        }
    }
    

  • Call it on an object with the dot operator: dog.bark();



Full lesson:

So far you've added data to a class with member variables and a constructor. The other half of OOP is behavior — actions an object can perform. That's what member functions are for.


Your task

Add a bark() member function that prints "Woof! I am " followed by the dog's name.

Woof! I am Rex
STEP 1 OF 2
    Ctrl + Enter to check

    Class Methods in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free