Rust chapters

Chapter 12 of 17

Objects and Structures

Try this in our Rust Compiler →

Grouping related data

When a value is more than a single number — a user with a name, email and age — you want to bundle the fields together under one name. Rust provides objects (or structs / records / dictionaries depending on the language) to do exactly that.

struct User { name: String, age: u32 }

impl User {
    fn greet(&self) -> String { format!("Hi {}", self.name) }
}

let u = User { name: String::from("Aman"), age: 20 };
println!("{}", u.greet());

Methods

Many languages let an object carry not only data but also functions ("methods") that operate on that data. This style is called object-oriented programming and is the dominant way to organise large programs.

When to make a new type

If you find yourself passing three or four related values into every function — say x, y and z of a 3-D point — that is a clear signal to introduce a new object type that holds them together. The code becomes shorter, safer and easier to extend.

Details for rust

Result models failure and ? propagates compatible errors. unwrap may panic and is unsuitable for unchecked input. Borrowing rules restrict incompatible mutation while a borrow is active.

Practice and verify

Change one meaningful value in the example and predict the result before running. Then test a boundary or empty value. Explain what changed and why, rather than only copying the output.

Try it yourself

Output
Run your project to see output here.
Ctrl/Cmd+Enter runs · Ctrl/Cmd+S downloads the project · Local auto-save is always on