Start learning free

LESSON 184 OF 348 · OBJECT-ORIENTED PROGRAMMING

Creating Objects in Rust in Rust

Lesson

TL ; DR:

  • An object is an instance of a struct — a real, usable copy made from the blueprint.


  • In Rust, you create a struct instance using the struct name followed by curly braces. No new keyword:

    let rex = Dog {};
    

  • Each binding creates a separate instance, even if they all come from the same struct.



Full lesson:

In the previous lesson you defined the Dog struct — the blueprint. But a blueprint isn't a dog. To get an actual dog you can interact with, you need to create an instance of the struct. An instance is also called an object.


Stack-allocated instances

The simplest way to create an instance in Rust is to use a struct literal:

let rex = Dog {};

This creates a Dog instance on the stack, bound to the name rex. Notice there's no new keyword — Rust uses struct literal syntax to create instances directly.


Many instances from one struct

You can create as many Dog instances as you want, and each one is independent:

let rex = Dog {};
let buddy = Dog {};
let luna = Dog {};

rex, buddy, and luna are all Dog instances, but they're different instances living at different stack addresses. Modifying one won't affect the others.


Heap allocation (advanced — not used here)

Rust does also support heap allocation via Box::new(), which allocates on the heap and is automatically freed when it goes out of scope:

let rex = Box::new(Dog {});
// Automatically dropped when rex goes out of scope

Don't use this style for these lessons — stack instances are simpler and Rust's ownership system handles cleanup automatically.


Your task

The Dog struct is already defined for you. Below it, declare three Dog instances named rex, buddy, and luna. The pre-filled validation will print one line per dog you've successfully created:

rex exists
buddy exists
luna exists
STEP 1 OF 3
    Ctrl + Enter to check

    Creating Objects 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