Start learning free

LESSON 288 OF 679 · FUNCTIONS & CLASSES

Creating Objects 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, each owned by its own binding. 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 as a unit struct (struct Dog;), so the name Dog by itself is a complete value. At the top of mainFunction, declare three Dog instances named rex, buddy, and luna, each wrapped in Some and typed Option<Dog>, for example let rex: Option<Dog> = Some(Dog);. 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