Start learning free

LESSON 185 OF 348 · OBJECT-ORIENTED PROGRAMMING

Constructors in Rust in Rust

Lesson

TL ; DR:

  • A constructor is a special method that runs automatically when you create an object. It's used to set up the object's initial state.


  • In Rust, a constructor is conventionally an associated function named new inside an impl block:

    struct Dog {
        name: String,
        age: i32,
    }
    
    impl Dog {
        fn new(name: String, age: i32) -> Self {
            Dog { name, age }
        }
    }
    

  • Then create objects with arguments: let rex = Dog::new(String::from("Rex"), 4); — the constructor fills in the members for you.



Full lesson:

In the previous lesson you set member variables one at a time after creating the object:

let mut dog = Dog { name: String::new(), age: 0 };
dog.name = String::from("Rex");
dog.age = 4;

That works, but it's verbose and easy to forget. Constructors let you initialize the members the moment the object is created.


Defining a constructor

A Rust constructor is conventionally an associated function named new inside an impl block:

  • It is defined with fn new(...) — just a regular associated function.

  • It returns Self — the type being constructed.

fn new(name: String, age: i32) -> Self {
    Dog { name, age }
}

Struct literal initialization

The parameter name and the field name have the same identifier. Rust uses the field init shorthand: when a variable name matches the field name, you can write Dog { name, age } instead of Dog { name: name, age: age }. No this pointer is needed.


Calling the constructor

let rex = Dog::new(String::from("Rex"), 4);
let luna = Dog::new(String::from("Luna"), 7);

By the time these lines finish, rex.name is already "Rex", rex.age is 4, and the same for Luna. Note: no heap allocation is needed for stack-allocated structs.


Your task

The Dog struct already has the name and age fields. Add a new associated function that takes a String name and an i32 age and returns a Dog using struct literal syntax. Then in mainFunction, create two dogs:

let rex = Dog::new(String::from("Rex"), 4);
let luna = Dog::new(String::from("Luna"), 7);

Expected output:

Rex is 4
Luna is 7
STEP 1 OF 2
    Ctrl + Enter to check

    Constructors 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