Start learning free

LESSON 183 OF 348 · OBJECT-ORIENTED PROGRAMMING

Defining a Class in Rust in Rust

Lesson

TL ; DR:

  • A struct is a blueprint for creating objects. It groups together related data and behavior under a single name.


  • In Rust, you define a struct with the struct keyword, followed by the struct name and a pair of curly braces:

    struct Dog {
    }
    

    The body of the struct can be empty — that's still a valid struct. We'll add data and behavior to it in the next lessons.



Full lesson:

So far, you've worked with built-in types like i32, &str, and arrays. But what if you want to model something the language doesn't have a type for — like a Dog, a BankAccount, or a Game?

That's what structs are for. A struct lets you define your own type by listing what data it holds and what actions it can perform.


Why structs?

Imagine you're writing a program about dogs. Each dog has a name, an age, and can bark. Without structs, you'd have to track each dog's name in one variable, age in another, and write a separate bark() function for each. That gets messy fast.

With a struct, you bundle all of that into one neat package called Dog:

struct Dog {
    // We'll add fields and methods in upcoming lessons.
}

The syntax

Defining an empty struct in Rust looks like this:

struct StructName {
}

Three things to notice:

  • The keyword struct tells Rust you're defining a new type.

  • StructName is the name you choose. By convention, Rust struct names use PascalCase — capitalized words with no underscores: Dog, BankAccount, HighScore.

  • The curly braces { } hold the body of the struct. Unlike C++, Rust does not require a semicolon after the closing brace when the struct has a body.


No classes: struct + impl:

Rust has no classes. You put the data in a struct, and its methods in a separate impl block. Methods take &self; functions without self are associated functions, called as Type::func().

struct Dog {
    name: String,
}

impl Dog {
    fn new(name: String) -> Dog {   // associated function: Dog::new(...)
        Dog { name }
    }
    fn bark(&self) {                // method: takes &self
        println!("{} says woof!", self.name);
    }
}

Your task

Define an empty struct called Dog. The pre-filled code in mainFunction will create an instance of your struct and print a confirmation message. If you define the struct correctly, the program will compile and print:

Defined the Dog class!
STEP 1 OF 1
    Ctrl + Enter to check

    Defining A Class 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