The types map¶
Level: reference · the map
One line: Every Rust type is built from a short list of primitives, two ways you combine them yourself (struct and enum), and a handful of std types assembled from those — this page is that tree, with the lesson for every branch.
Type questions arrive under many names — data types, compound types, collections, smart pointers, aliases — and the lessons that answer them sit in a dozen sections, because each one lives beside the idea it is used for. This page is the one place they hang from a single tree. To look a topic up by any name at all, use TOPICS.md instead.
The tree¶
flowchart LR
T["Rust types"]
T --> P["PRIMITIVE<br/>built into the language"]
P --> SC["scalar<br/>integers · floats · bool · char"]
P --> PC["primitive compound<br/>tuple · array"]
P --> UNS["unsized<br/>str · slice [T] · dyn Trait"]
P --> EMPTY["nothing to hold<br/>unit () · never !"]
T --> UD["YOUR OWN<br/>declared with a keyword"]
UD --> ST["struct<br/>named fields · tuple struct · unit struct"]
UD --> EN["enum<br/>one of several variants"]
UD --> UN["union<br/>fields on top of each other"]
T --> STD["BUILT BY STD<br/>ordinary structs and enums"]
STD --> OR["Option · Result"]
STD --> COL["Vec · VecDeque · HashMap · HashSet · BTreeMap"]
STD --> TXT["String · OsString · CString · PathBuf"]
T --> PTR["POINTERS"]
PTR --> REF["references &T · &mut T"]
PTR --> RAW["raw pointers *const T · *mut T"]
PTR --> SMART["Box · Rc · Arc · Cell · RefCell · Cow"]
T --> FN["CODE AS A VALUE<br/>fn items · fn pointers · closures"]
T --> NAME["NAMING A TYPE<br/>type alias · newtype · T · impl Trait · dyn Trait"]
Compound types: the two that are primitive¶
A compound type groups several values into one type. The Book, §3.2 ↗ says Rust has two primitive compound types: tuples and arrays. That sentence is easy to misread in two directions, so here is what it does and does not include:
| Type | Primitive compound? | Why |
|---|---|---|
tuple (i32, &str) |
yes | built into the language; values of different types, fields numbered — Tuples |
array [u8; 3] |
yes | built into the language; one element type, length fixed in the type — Arrays: the map |
Vec<T> |
no | a struct in std over a heap allocation — a collection, not a primitive |
HashMap<K, V>, String |
no | structs in std, same reason |
struct, enum |
no | compound, but user-defined: you declare them, the language does not provide them |
slice [T], str |
primitive, not compound | a run of values with no size known at compile time — you only ever hold a pointer to one |
Primitive types¶
| Type | Lesson | Notes |
|---|---|---|
i8…i128, u8…u128, isize, usize |
The integer types · Writing a number down · Meet the byte | u8 is the unit every size is counted in |
f32, f64 |
What a float actually stores · Making a float whole | f16 and f128 are nightly-only on 1.98.0 |
bool |
Meet the bool |
not a number, no truthiness |
char |
Meet the char · Why a char is 32 bits |
one Unicode scalar value, always four bytes |
| tuple | Tuples | a struct whose fields are numbered |
array [T; N] |
Arrays: the map · Arrays and slices · Array or Vec? · Const generics |
the length is part of the type |
slice [T] |
Arrays and slices · slice methods |
held as &[T], a pointer and a length |
str |
str is unsized · String slices |
held as &str |
unit () |
The unit type | the empty tuple: one value, zero bytes |
never ! |
The never type | the type of an expression that does not finish; naming it as a type is nightly-only |
references, pointers, fn |
see Pointers and Code as a value below |
All of these are listed in std's primitive type docs ↗, one page each.
Your own types¶
| You write | Lesson | What to read next |
|---|---|---|
struct Point { x: i32, y: i32 } |
What a struct is | STRUCTS.md, the whole structs map |
struct Meters(f64); — tuple struct, newtype |
A score is not a number: the newtype | Units are types |
struct Marker; — unit struct |
What a struct is | Marker traits |
enum Shape { Circle(f64), Square(f64) } |
What an enum is · Variants that carry data | Generic enums |
union |
What a union is | Type layout |
| methods for any of them | impl blocks |
What a trait is |
A struct is a product type and an enum is a sum type — the glossary entry for algebraic data types says why those words fit.
Built by std¶
These look like language features and are ordinary library types, written with struct and enum like yours.
| Type | Lesson | Map |
|---|---|---|
Option<T> |
Some and None |
OPTION.md |
Result<T, E> |
Option vs Result |
Errors |
Vec<T> |
Vec · Vec methods |
Collections |
VecDeque<T> |
VecDeque |
|
HashMap<K, V>, HashSet<T> |
A first HashMap · HashMap · A first HashSet · HashSet |
Set operations |
BTreeMap, BTreeSet |
BTreeMap and BTreeSet |
Set operations · Sets of sets |
String |
String vs &str · The anatomy of a String |
STRINGS.md |
OsString, CString |
Six kinds of string | |
PathBuf, Path |
Path and PathBuf |
|
Duration, Instant, SystemTime |
Two clocks · A Duration cannot be negative |
Pointers¶
| Type | Lesson | What it adds |
|---|---|---|
&T, &mut T |
Address, pointer, reference · Borrowing · What &'a T claims · Mutable binding, mutable reference |
a checked loan: many readers or one writer |
*const T, *mut T |
Raw pointers · What unsafe turns off |
an address and nothing else — dereferencing needs unsafe |
&[T], &str, &dyn Trait |
Wide pointers | an address plus a length or a vtable — two words |
Box<T> |
Box |
one owner, on the heap |
Rc<T> |
Rc: the clone that copies a pointer |
several owners, one thread |
Arc<T> |
Sharing across threads: Arc |
several owners, many threads |
Cell<T>, RefCell<T> |
Interior mutability | writing through a &T, checked at run time |
Cow<'a, B> |
Cow: borrow until somebody writes |
borrowed or owned, decided at run time |
Option<Box<T>> |
Nullable pointers | a pointer that may be absent, at no extra size |
| any of the above, in general | Smart pointers · What a smart pointer is | Deref to act like a reference, Drop to do a job |
Code as a value¶
| Type | Lesson |
|---|---|
fn(u32) -> u32 — function pointer |
Function pointers |
a closure's anonymous type, and Fn / FnMut / FnOnce |
What a closure is · The three closure traits |
| a function declared inside a function | Items inside a function |
Naming a type¶
| You write | Lesson | What it is not |
|---|---|---|
type Km = u32; |
A type alias is not a new type · The Result alias |
a distinct type — that is the newtype |
struct Km(u32); |
A score is not a number: the newtype | free of boilerplate — it has none of u32's methods |
fn f<T>(x: T) |
What a generic is · Where the bound goes | a runtime type — each T is compiled separately |
-> impl Trait |
Returning a trait | several types — one concrete type, hidden |
&dyn Trait, Box<dyn Trait> |
Static vs dynamic dispatch | free — a vtable call, and a wide pointer |
PhantomData<T> |
Phantom types | data — zero bytes, a tag for the compiler |
Between types¶
| Question | Lesson |
|---|---|
| Which type did the compiler pick? | Type inference · What a type annotation does |
| How do I turn one into another? | Conversion: as · From and Into · TryFrom · coercion |
| Is it copied or moved? | Copy or move? · Copy vs Clone |
| How big is it, and where do the bytes go? | Stack and heap · What is a record, in memory? · Type layout |
If you are coming from another language¶
- Python. Python's
listis Rust'sVec,tupleis a tuple,dictisHashMapandsetisHashSet— and Python has nothing like the array, whose length the compiler knows, or like the split between an owner (String) and a view (&str). The Python library'sstris notbytes↗ is the one type split both languages make. - C. Scalars, arrays and
structtransfer directly,uniontoo. What is new: a taggedenumthe compiler checks, a slice that carries its length (the C library's a string is bytes up to a NUL ↗ shows the alternative), and no implicit conversions between numeric types. - Java. No primitive/boxed split and no
null:Option<T>is the nullable type, and a genericVec<i32>storesi32s inline instead of boxedIntegers. - Go. Arrays with the length in the type and slices as views are the same design; Rust adds
enumwith data, which Go spells with interfaces and type switches. - ABAP. A structure is a
struct, an internal table is aVec, and a fixed-length field such asc LENGTH 10is the closest thing to an array — the length is part of the type in both.
Po polsku¶
Ta strona to drzewo typów: typy wbudowane (skalarne, dwa złożone — krotka i tablica — oraz typy bez rozmiaru, jak str), typy definiowane samodzielnie (struct, enum, union), typy zbudowane z nich przez bibliotekę standardową (Option, Vec, String), wskaźniki i sposoby nazywania typów. Zdanie z The Book, że Rust ma dwa wbudowane typy złożone — krotki i tablice — nie obejmuje Vec: wektor to zwykła struktura z biblioteki standardowej, czyli kolekcja, a nie typ wbudowany.
Szukaj po polsku: typy danych w Ruście · typy złożone · krotka i tablica · rust primitive types · rust compound types tuple array