Start learning free

LESSON 289 OF 679 · FUNCTIONS & CLASSES

Constructors in Rust

Lesson

TL ; DR:

  • A constructor is code that sets up an object's initial state when you create it. Rust has no special constructor syntax: by convention it is an ordinary associated function.


  • 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: &str, age: i32) -> Dog {
            Dog { name: name.to_string(), age }
        }
    }
    

  • Then create objects with arguments: let rex = Dog::new("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 Dog — the type being constructed (inside an impl block you may also write Self for it).

fn new(name: &str, age: i32) -> Dog {
    Dog { name: name.to_string(), age }
}

Struct literal initialization

The parameter name is a borrowed &str, but the field owns a String, so name.to_string() makes an owned copy. The parameter age and the field age have the same identifier, so Rust's field init shorthand lets you write age instead of age: age. No this pointer is needed.


Calling the constructor

let rex = Dog::new("Rex", 4);
let luna = Dog::new("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 &str name and an i32 age and returns a Dog using struct literal syntax. Then in mainFunction, create two dogs:

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

Expected output:

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