Structs and Methods in Rust
by Hexagon, 3 min read rust guide
Structs let you bundle related data together under one name, and give it your own type. Add methods, and you have something that works a lot like objects and classes in other languages, but without inheritance. Let's build some.
Defining a Struct
A struct is a named collection of fields, each with a type:
Struct names are written in PascalCase, and fields in snake_case. Unlike a
JavaScript object, you can't add new fields later. The struct definition says
exactly what's in it.
Changing fields
To change a field, the whole variable must be mut. You can't mark a single
field as mutable:
Shorthands
If a variable has the same name as a field, you can skip the field: value
part. And you can create a struct from another one, with ..:
This looks a lot like the spread operator in JavaScript, but note that it moves
fields that aren't Copy. Here it's fine, as age and active are copied, and
we gave bob its own name.
Printing Structs
If you try to print a struct with {:?}, Rust complains that it doesn't know
how. You can ask the compiler to write that code for you, with derive:
You'll put #[derive(Debug)] on most of your structs. We'll see more things
that can be derived in the article about traits.
Methods
Methods are functions that belong to a type. They're defined in an impl block:
self is like this in JavaScript, but you always write it out, and you
decide how the method gets it:
&selfborrows the value to read it. This is the most common one.&mut selfborrows the value to change it.selftakes ownership, and consumes the value. Used for methods that turn a value into something else.
All the ownership rules from before apply. You can't call scale on a
rectangle that isn't mut.
Associated Functions
Functions in an impl block that don't take self are called associated
functions. They're called on the type, with ::. You've used one already:
String::from.
The most common use is a constructor, which by convention is called new:
Self is a shortcut for the type the impl block is for, here Rectangle.
Rust has no special constructor syntax, and no new keyword. new is just a
function that returns a struct, so you can have as many constructors as you
like, with names that say what they do.
Tuple Structs and Unit Structs
Sometimes, naming every field is overkill. A tuple struct has fields without names:
;
;
;
Wrapping a plain number in a tuple struct like Meters is called the
"newtype" pattern. It costs nothing at runtime, but the compiler now stops you
from mixing up meters and feet. Mixing up units like that has cost at least one real Mars probe.
There are also unit structs, with no fields at all, written struct Marker;.
They're useful with traits, which we'll get to later.
No Inheritance
Coming from JavaScript classes, you might look for extends. Rust doesn't have
it. Instead, you put structs inside other structs, and share behavior with
traits. In practice, this leads to simpler code, as there's no long chain of
parent classes to keep in your head.
Conclusion
Structs are how you model data in Rust, and impl blocks are how you give that
data behavior. Here's a small example that brings it together:
What happens if average is called before any scores are added? Try it. You'll
get NaN, as it divides zero by zero. In the next article, we'll see how enums
and Option let us handle that properly.