TL;DR
Rust passes a method the value it’s being called on as its first argument, which must have the special name self
. Since self
’s type is obviously the one named at the top of the impl
block, or a reference to that, Rust lets you omit the type, and write self
, &self
, or &mut self
as shorthand for self: Queue
, self: &Queue
, or self: &mut Queue
.
Every impl
block, generic or not, defines the special type parameter Self
(note the CamelCase
name) to be whatever type we’re adding methods to.
Brief
Rust structs, sometimes called structures, resemble struct
types in C and C++, classes in Python, and objects in JavaScript. A struct assembles several values of assorted types together into a single value so you can deal with them as a unit. Given a struct, you can read and modify its individual components. And a struct can have methods associated with it that operate on its components.
Rust has three kinds of struct types, named-field, tuple-like, and unit-like, which differ in how you refer to their components: a named-field struct gives a name to each component, whereas a tuple-like struct identifies them by the order in which they appear. Unit-like structs have no components at all.
Named-Field Structs
The definition of a named-field struct type looks like this:
|
|
The convention in Rust is for all types, structs included, to have names that capitalize the first letter of each word, like GrayscaleMap
, a convention called CamelCase (or PascalCase). Fields and methods are lowercase, with words separated by underscores. This is called snake_case.
You can construct a value of this type with a struct expression, like this:
|
|
A struct expression starts with the type name and lists the name and value of each field, all enclosed in curly braces. There’s also shorthand for populating fields from local variables or arguments with the same name:
|
|
You can use key: value
syntax for some fields and shorthand for others in the same struct expression.
To access a struct’s fields, use the .
operator.
Like all other items, structs are private by default, visible only in the module where they’re declared and its submodules. You can make a struct visible outside its module by prefixing its definition with pub
. The same goes for each of its fields, which are also private by default:
|
|
Even if a struct is declared pub
, its fields can be private:
|
|
Other modules can use this struct and any public associated functions it might have, but can’t access the private fields by name or use struct expressions to create new GrayscaleMap
values. That is, creating a struct value requires all the struct’s fields to be visible. This is why you can’t write a struct expression to create a new String
or Vec
. These standard types are structs, but all their fields are private. To create one, you must use public type-associated functions like Vec::new()
.
When creating a named-field struct value, you can use another struct of the same type to supply values for fields you omit. In a struct expression, if the named fields are followed by .. EXPR
, then any fields not mentioned take their values from EXPR
, which must be another value of the same struct type.
Suppose we have a struct representing a monster in a game:
|
|
Tuple-Like Structs
The second kind of struct type is called a tuple-like struct, because it resembles a tuple:
|
|
You construct a value of this type much as you would construct a tuple, except that you must include the struct name:
|
|
The values held by a tuple-like struct are called elements, just as the values of a tuple are. You access them just as you would a tuple’s:
|
|
Individual elements of a tuple-like struct may be public or not.
|
|
You construct a value of this type much as you would construct a tuple, except that you must include the struct name:
|
|
The expression Bounds(1024, 768)
looks like a function call, and in fact it is: defining the type also implicitly defines a function:
|
|
At the most fundamental level, named-field and tuple-like structs are very similar. The choice of which to use comes down to questions of legibility, ambiguity, and brevity. If you will use the .
operator to get at a value’s components much at all, identifying fields by name provides the reader more information and is probably more robust against typos. If you will usually use pattern matching to find the elements, tuple-like structs can work nicely.
Tuple-like structs are good for newtypes, structs with a single component that you define to get stricter type checking. For example, if you are working with ASCII-only text, you might define a newtype like this:
|
|
Using this type for your ASCII strings is much better than simply passing around Vec<u8>
buffers and explaining what they are in the comments. The newtype helps Rust catch mistakes where some other byte buffer is passed to a function expecting ASCII text.
Unit-Like Structs
A unit-like struct is a struct with no fields at all:
|
|
A value of unit-like struct occupies no memory, much like the unit type ()
. Rust doesn’t bother actually storing unit-like struct values in memory or generating code to operate on them, because it can tell everything it might need to know about the value from its type alone. But logically, an empty struct is a type with values like any other—or more precisely, a type of which there is only a single value.
Whereas an expression like 3..5
is shorthand for the struct value Range { start: 3, end: 5 }
, the expression ..
, a range omitting both endpoints, is shorthand for the unit-like struct value RangeFull
.
|
|
Struct Layout
In memory, both named-field and tuple-like structs are the same thing: a collection of values, of possibly mixed types, laid out in a particular way in memory.
For the following struct:
|
|
A GrayscaleMap
value is laid out in memory as diagrammed.

Unlike C and C++, Rust doesn’t make specific promises about how it will order a struct’s fields or elements in memory; this diagram shows only one possible arrangement. However, Rust does promise to store fields’ values directly in the struct’s block of memory. Whereas JavaScript, Python, and Java would put the pixels and size values each in their own heap-allocated blocks and have GrayscaleMap
’s fields point at them, Rust embeds pixels
and size
directly in the GrayscaleMap
value. Only the heap-allocated buffer owned by the pixels
vector remains in its own block.
You can ask Rust to lay out structures in a way compatible with C and C++, using the #[repr(C)]
attribute.
Defining Methods with impl
You can define methods on your own struct types. Rather than appearing inside the struct definition, as in C++ or Java, Rust methods appear in a separate impl
block.
An impl
block is simply a collection of fn
definitions, each of which becomes a method on the struct type named at the top of the block.
Functions defined in an impl
block are called associated functions, since they’re associated with a specific type. The opposite of an associated function is a free function, one that is not defined as an impl
block’s item.
Rust passes a method the value it’s being called on as its first argument, which must have the special name self
. Since self
’s type is obviously the one named at the top of the impl
block, or a reference to that, Rust lets you omit the type, and write self
, &self
, or &mut self
as shorthand for self: Queue
, self: &Queue
, or self: &mut Queue
.
Unlike C++ and Java, where the members of the “this” object are directly visible in method bodies as unqualified identifiers, a Rust method must explicitly use self
to refer to the value it was called on, similar to the way Python methods use self
, and the way JavaScript methods use this
.
If a method wants to take ownership of self
, it can take self
by value.
Sometimes, taking self
by value, or even by reference, isn’t enough, so Rust also lets you pass self
via smart pointer types.
Passing Self as a Box, Rc, or Arc
A method’s self
argument can also be a Box<Self
>, Rc<Self>
, or Arc<Self>
. Such a method can only be called on a value of the given pointer type. Calling the method passes ownership of the pointer to it.
You won’t usually need to do this. A method that expects self
by reference works fine when called on any of those pointer types:
|
|
For method calls and field access, Rust automatically borrows a reference from pointer types like Box
, Rc
, and Arc
, so &self
and &mut self
are almost always the right thing in a method signature, along with the occasional self
.
If some method needs ownership of a pointer to Self
, and its callers have such a pointer handy, Rust will let you pass it as the method’s self
argument. To do so, you must spell out the type of self
, as if it were an ordinary parameter:
|
|
Type-Associated Functions
An impl
block for a given type can also define functions that don’t take self
as an argument at all. These are still associated functions, since they’re in an impl
block, but they’re not methods, since they don’t take a self
argument. To distinguish them from methods, we call them type-associated functions.
They’re often used to provide constructor functions, like this:
|
|
It’s conventional in Rust for constructor functions to be named new
. There’s nothing special about the name new
. It’s not a keyword, and types often have other associated functions that serve as constructors, like Vec::with_capacity
.
Although you can have many separate impl
blocks for a single type, they must all be in the same crate that defines that type. However, Rust does let you attach your own methods to other types.
There are several advantages to separating a type’s methods from its definition:
- It’s always easy to find a type’s data members. In large C++ class definitions, you might need to skim hundreds of lines of member function definitions to be sure you haven’t missed any of the class’s data members; in Rust, they’re all in one place.
- Although one can imagine fitting methods into the syntax for named-field structs, it’s not so neat for tuple-like and unit-like structs. Pulling methods out into an impl block allows a single syntax for all three. In fact, Rust uses this same syntax for defining methods on types that are not structs at all, such as
enum
types and primitive types likei32
.- The fact that any type can have methods is one reason Rust doesn’t use the term object much, preferring to call everything a value.
- The same
impl
syntax also serves neatly for implementing traits.
Associated Consts
Another feature of languages like C# and Java that Rust adopts in its type system is the idea of values associated with a type, rather than a specific instance of that type. In Rust, these are known as associated consts.
Associated consts are constant values. They’re often used to specify commonly used values of a type:
|
|
Nor does an associated const have to be of the same type as the type it’s associated with; we could use this feature to add IDs or names to types. For example, if there were several types similar to Vector2
that needed to be written to a file and then loaded into memory later, an associated const could be used to add names or numeric IDs that could be written next to the data to identify its type:
|
|
Generic Structs
Rust structs can be generic, meaning that their definition is a template into which you can plug whatever types you like. For example, here’s a definition for Queue
that can hold values of any type:
|
|
You can read the <T>
in Queue<T>
as “for any element type T
…”. So this definition reads, “For any type T
, a Queue<T>
is two fields of type Vec<T>
.” In fact, Vec
itself is a generic struct, defined in just this way.
In generic struct definitions, the type names used in <
angle brackets>
are called type parameters. An impl
block for a generic struct looks like this:
|
|
You can read the line impl<T> Queue<T>
as something like, “for any type T
, here are some associated functions available on Queue<T>
.” Then, you can use the type parameter T
as a type in the associated function definitions.
The syntax may look a bit redundant, but the impl<T>
makes it clear that the impl
block covers any type T
.
Writing out Queue<T>
everywhere becomes a mouthful and a distraction. As another shorthand, every impl
block, generic or not, defines the special type parameter Self
(note the CamelCase
name) to be whatever type we’re adding methods to. In the preceding code, Self
would be Queue<T>
, so we can abbreviate Queue::new
’s definition a bit further:
|
|
In the body of new
, we didn’t need to write the type parameter in the construction expression; simply writing Queue { ... }
was good enough. This is Rust’s type inference at work: since there’s only one type that works for that function’s return value—namely, Queue<T>
—Rust supplies the parameter for us. However, you’ll always need to supply type parameters in function signatures and type definitions. Rust doesn’t infer those; instead, it uses those explicit types as the basis from which it infers types within function bodies. Self
can also be used in this way; we could have written Self { ... }
instead.
For associated function calls, you can supply the type parameter explicitly using the ::<>
(turbofish) notation. But in practice, you can usually just let Rust figure it out for you:
|
|
This is exactly what we’ve been doing with Vec
, another generic struct type.
Generic Structs with Lifetime Parameters
If a struct type contains references, you must name those references’ lifetimes. For example, here’s a structure that might hold references to the greatest and least elements of some slice:
|
|
You can think of a declaration like struct Queue<T>
as meaning that, given any specific type T
, you can make a Queue<T>
that holds that type. Similarly, you can think of struct Extrema<'elt>
as meaning that, given any specific lifetime 'elt
, you can make an Extrema<'elt>
that holds references with that lifetime.
Here’s a function to scan a slice and return an Extrema
value whose fields refer to its elements:
|
|
Since find_extrema
borrows elements of slice, which has lifetime 's
, the Extrema
struct we return also uses ’s as the lifetime of its references. Rust always infers lifetime parameters for calls, so calls to find_extrema
needn’t mention them:
|
|
Because it’s so common for the return type to use the same lifetime as an argument, Rust lets us omit the lifetimes when there’s one obvious candidate. We could also have written find_extrema
’s signature like this, with no change in meaning:
|
|
Granted, we might have meant Extrema<'static>
, but that’s pretty unusual. Rust provides a shorthand for the common case.
Generic Structs with Constant Parameters
A generic struct can also take parameters that are constant values. For example, you could define a type representing polynomials of arbitrary degree like so:
|
|
Polynomial<3>
is a quadratic polynomial, for example. The <const N: usize>
clause says that the Polynomial
type expects a usize
value as its generic parameter, which it uses to decide how many coefficients to store.
Unlike Vec
, which has fields holding its length and capacity and stores its elements in the heap, Polynomial
stores its coefficients directly in the value, and nothing else. The length is given by the type. (The capacity isn’t needed, because Polynomial
s can’t grow dynamically.)
We can use the parameter N
in the type’s associated functions:
|
|
As with type and lifetime parameters, Rust can often infer the right values for constant parameters:
|
|
Since we pass Polynomial::new
an array with six elements, Rust knows we must be constructing a Polynomial<6>
. The eval
method knows how many iterations the for
loop should run simply by consulting its Self
type. Since the length is known at compile time, the compiler will probably replace the loop entirely with straight-line code.
A const
generic parameter may be any integer type, char
, or bool
. Floating-point numbers, enums, and other types are not permitted.
If the struct takes other kinds of generic parameters, lifetime parameters must come first, followed by types, followed by any const
values. For example, a type that holds an array of references could be declared like this:
|
|
If the value you want to supply for a const
generic parameter is not simply a literal or a single identifier, then you must wrap it in braces, as in Polynomial<{5 + 1}>
. This rule allows Rust to report syntax errors more accurately.
Deriving Common Traits for Struct Types
Structs can be very easy to write:
|
|
However, if you were to start using this Point
type, you would quickly notice that it’s a bit of a pain. As written, Point
is not copyable or cloneable. You can’t print it with println!("{:?}", point);
and it does not support the ==
and !=
operators.
Each of these features has a name in Rust—Copy
, Clone
, Debug
, and PartialEq
. They are called traits. In the case of these standard traits, and several others, you don’t need to implement them by hand unless you want some kind of custom behavior. Rust can automatically implement them for you, with mechanical accuracy. Just add a #[derive]
attribute to the struct:
|
|
Each of these traits can be implemented automatically for a struct, provided that each of its fields implements the trait. We can ask Rust to derive PartialEq
for Point
because its two fields are both of type f64
, which already implements PartialEq
.
Rust can also derive PartialOrd
, which would add support for the comparison operators <
, >
, <=
, and >=
. We haven’t done so here, because comparing two points to see if one is “less than” the other is actually a pretty weird thing to do. There’s no one conventional order on points. So we choose not to support those operators for Point
values. Cases like this are one reason that Rust makes us write the #[derive]
attribute rather than automatically deriving every trait it can. Another reason is that implementing a trait is automatically a public feature, so copyability, cloneability, and so forth are all part of your struct’s public API and should be chosen deliberately.
Interior Mutability
Mutability is like anything else: in excess, it causes problems, but you often want just a little bit of it. For example, say your spider robot control system has a central struct, SpiderRobot
, that contains settings and I/O handles. It’s set up when the robot boots, and the values never change:
|
|
Every major system of the robot is handled by a different struct, and each one has a pointer back to the SpiderRobot
:
|
|
A value in an Rc
box is always shared and therefore always immutable.
Now suppose you want to add a little logging to the SpiderRobot
struct, using the standard File
type. There’s a problem: a File
has to be mut
. All the methods for writing to it require a mut
reference. What we need is a little bit of mutable data (a File
) inside an otherwise immutable value (the SpiderRobot
struct). This is called interior mutability.
|
|
The two most straightforward types for interior mutability are Cell<T>
and RefCell<T>
, both in the std::cell
module.
A Cell<T>
is a struct that contains a single private value of type T
. The only special thing about a Cell
is that you can get and set the field even if you don’t have mut
access to the Cell
itself:
Cell::new(value)
: Creates a newCell
, moving the given value into it.cell.get()
: Returns a copy of the value in thecell
.cell.set(value)
: Stores the given value in thecell
, dropping the previously stored value. This method takesself
as a non-mut
reference:1
fn set(&self, value: T) // note: not `&mut self`
- This is unusual for methods named
set
. Rust has trained us to expect that we needmut
access if we want to make changes to data. But by the same token, this one unusual detail is the whole point ofCell
s. They’re simply a safe way of bending the rules on immutability—no more, no less.
- This is unusual for methods named
A Cell
would be handy if you were adding a simple counter to your SpiderRobot
. Then even non-mut
methods of SpiderRobot
can access that u32
, using the .get()
and .set()
methods:
|
|
This is easy enough, but it doesn’t solve our logging problem. Cell
does not let you call mut
methods on a shared value. The .get()
method returns a copy of the value in the cell, so it works only if T
implements the Copy
trait. For logging, we need a mutable File
, and File
isn’t copyable.
The right tool in this case is a RefCell
. Like Cell<T>
, RefCell<T>
is a generic type that contains a single value of type T
. Unlike Cell
, RefCell
supports borrowing references to its T
value:
RefCell::new(value)
: Creates a newRefCell
, moving value into it.ref_cell.borrow()
: Returns aRef<T>
, which is essentially just a shared reference to the value stored inref_cell
.- This method panics if the value is already mutably borrowed.
ref_cell.borrow_mut()
: Returns aRefMut<T>
, essentially a mutable reference to the value inref_cell
.- This method panics if the value is already borrowed.
ref_cell.try_borrow()
,ref_cell.try_borrow_mut()
: Work just likeborrow()
andborrow_mut()
, but return aResult
. Instead of panicking if the value is already mutably borrowed, they return anErr
value.
The two borrow
methods panic only if you try to break the Rust rule that mut references are exclusive references:
|
|
To avoid panicking, you could put these two borrows into separate blocks. That way, r
would be dropped before you try to borrow w
.
This is a lot like how normal references work. The only difference is that normally, when you borrow a reference to a variable, Rust checks at compile time to ensure that you’re using the reference safely. If the checks fail, you get a compiler error. RefCell
enforces the same rule using run-time checks. So if you’re breaking the rules, you get a panic (or an Err
, for try_borrow
and try_borrow_mut
).
Now we’re ready to put RefCell
to work in our SpiderRobot
type:
|
|
The variable file
has type RefMut<File>
. It can be used just like a mutable reference to a File
.
Cells are easy to use. Having to call .get()
and .set()
or .borrow()
and .borrow_mut()
is slightly awkward, but that’s just the price we pay for bending the rules. The other drawback is less obvious and more serious: cells—and any types that contain them—are not thread-safe. Rust therefore will not allow multiple threads to access them at once.
Whether a struct has named fields or is tuple-like, it is an aggregation of other values: if I have a SpiderSenses
struct, then I have an Rc
pointer to a shared SpiderRobot
struct, and I have eyes, and I have an accelerometer, and so on. So the essence of a struct is the word “and”: I have an X and a Y.