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
structkeyword, 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
structtells Rust you're defining a new type.StructNameis 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!Free plan: 30 tutor messages. Premium is unlimited.