Structures in Rust are defined using the struct
keyword. The most common form of structure consists of a set of named fields:
struct Foo {
my_bool: bool,
my_num: isize,
my_string: String,
}
The above declares a struct
with three fields: my_bool
, my_num
, and my_string
, of the types bool
, isize
, and String
respectively.
Another way to create struct
s in Rust is to create a tuple struct:
struct Bar (bool, isize, String);
This defines a new type, Bar
, that has three unnamed fields, of type bool
, isize
, and String
, in that order. This is known as the newtype pattern, because it effectively introduces a new "name" for a particular type. However, it does so in a more powerful manner than the aliases created using the type
keyword; Bar
is here a fully functional type, meaning you can write your own methods for it (below).
Finally, declare a struct
with no fields, called a unit-like struct:
struct Baz;
This can be useful for mocking or testing (when you want to trivially implement a trait), or as a marker type. In general, however, you are unlikely to come across many unit-like structs.
Note that struct
fields in Rust are all private by default --- that is, they cannot be accessed from code outside of the module which defines the type. You can prefix a field with the pub
keyword to make that field publicly accessible. In addition, the struct
type itself is private. To make the type available to other modules, the struct
definition must also be prefixed with pub
:
pub struct X {
my_field: bool,
pub our_field: bool,
}