âčïž Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0.1 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://doc.rust-lang.org/book/ch03-02-data-types.html |
| Last Crawled | 2026-04-08 03:23:47 (4 days ago) |
| First Indexed | 2018-12-08 02:18:41 (7 years ago) |
| HTTP Status Code | 200 |
| Meta Title | Data Types - The Rust Programming Language |
| Meta Description | null |
| Meta Canonical | null |
| Boilerpipe Text | Every value in Rust is of a certain
data type
, which tells Rust what kind of
data is being specified so that it knows how to work with that data. Weâll look
at two data type subsets: scalar and compound.
Keep in mind that Rust is a
statically typed
language, which means that it
must know the types of all variables at compile time. The compiler can usually
infer what type we want to use based on the value and how we use it. In cases
when many types are possible, such as when we converted a
String
to a numeric
type using
parse
in the
âComparing the Guess to the Secret
Numberâ
section in
Chapter 2, we must add a type annotation, like this:
#![allow(unused)]
fn
main
() {
let
guess:
u32
=
"42"
.parse().expect(
"Not a number!"
);
}
If we donât add the
: u32
type annotation shown in the preceding code, Rust
will display the following error, which means the compiler needs more
information from us to know which type we want to use:
$
cargo build
Compiling no_type_annotations v0.1.0 (file:///projects/no_type_annotations)
error[E0284]: type annotations needed
-->
src/main.rs:2:9
|
2 | let guess = "42".parse().expect("Not a number!");
| ^^^^^ ----- type must be known at this point
|
= note: cannot satisfy `<_ as FromStr>::Err == _`
help: consider giving `guess` an explicit type
|
2 | let guess: /* Type */ = "42".parse().expect("Not a number!");
| ++++++++++++
For more information about this error, try `rustc --explain E0284`.
error: could not compile `no_type_annotations` (bin "no_type_annotations") due to 1 previous error
Youâll see different type annotations for other data types.
Scalar Types
A
scalar
type represents a single value. Rust has four primary scalar types:
integers, floating-point numbers, Booleans, and characters. You may recognize
these from other programming languages. Letâs jump into how they work in Rust.
Integer Types
An
integer
is a number without a fractional component. We used one integer
type in Chapter 2, the
u32
type. This type declaration indicates that the
value itâs associated with should be an unsigned integer (signed integer types
start with
i
instead of
u
) that takes up 32 bits of space. Table 3-1 shows
the built-in integer types in Rust. We can use any of these variants to declare
the type of an integer value.
Table 3-1: Integer Types in Rust
Length
Signed
Unsigned
8-bit
i8
u8
16-bit
i16
u16
32-bit
i32
u32
64-bit
i64
u64
128-bit
i128
u128
Architecture-dependent
isize
usize
Each variant can be either signed or unsigned and has an explicit size.
Signed
and
unsigned
refer to whether itâs possible for the number to be
negativeâin other words, whether the number needs to have a sign with it
(signed) or whether it will only ever be positive and can therefore be
represented without a sign (unsigned). Itâs like writing numbers on paper: When
the sign matters, a number is shown with a plus sign or a minus sign; however,
when itâs safe to assume the number is positive, itâs shown with no sign.
Signed numbers are stored using
twoâs complement
representation.
Each signed variant can store numbers from â(2
n â 1
) to 2
n â
1
â 1 inclusive, where
n
is the number of bits that variant uses. So, an
i8
can store numbers from â(2
7
) to 2
7
â 1, which equals
â128 to 127. Unsigned variants can store numbers from 0 to 2
n
â 1,
so a
u8
can store numbers from 0 to 2
8
â 1, which equals 0 to 255.
Additionally, the
isize
and
usize
types depend on the architecture of the
computer your program is running on: 64 bits if youâre on a 64-bit architecture
and 32 bits if youâre on a 32-bit architecture.
You can write integer literals in any of the forms shown in Table 3-2. Note
that number literals that can be multiple numeric types allow a type suffix,
such as
57u8
, to designate the type. Number literals can also use
_
as a
visual separator to make the number easier to read, such as
1_000
, which will
have the same value as if you had specified
1000
.
Table 3-2: Integer Literals in Rust
Number literals
Example
Decimal
98_222
Hex
0xff
Octal
0o77
Binary
0b1111_0000
Byte (
u8
only)
b'A'
So how do you know which type of integer to use? If youâre unsure, Rustâs
defaults are generally good places to start: Integer types default to
i32
.
The primary situation in which youâd use
isize
or
usize
is when indexing
some sort of collection.
Integer Overflow
Letâs say you have a variable of type
u8
that can hold values between 0 and
255. If you try to change the variable to a value outside that range, such as
256,
integer overflow
will occur, which can result in one of two behaviors.
When youâre compiling in debug mode, Rust includes checks for integer overflow
that cause your program to
panic
at runtime if this behavior occurs. Rust
uses the term
panicking
when a program exits with an error; weâll discuss
panics in more depth in the
âUnrecoverable Errors with
panic!
â
section in Chapter
9.
When youâre compiling in release mode with the
--release
flag, Rust does
not
include checks for integer overflow that cause panics. Instead, if
overflow occurs, Rust performs
twoâs complement wrapping
. In short, values
greater than the maximum value the type can hold âwrap aroundâ to the minimum
of the values the type can hold. In the case of a
u8
, the value 256 becomes
0, the value 257 becomes 1, and so on. The program wonât panic, but the
variable will have a value that probably isnât what you were expecting it to
have. Relying on integer overflowâs wrapping behavior is considered an error.
To explicitly handle the possibility of overflow, you can use these families
of methods provided by the standard library for primitive numeric types:
Wrap in all modes with the
wrapping_*
methods, such as
wrapping_add
.
Return the
None
value if there is overflow with the
checked_*
methods.
Return the value and a Boolean indicating whether there was overflow with
the
overflowing_*
methods.
Saturate at the valueâs minimum or maximum values with the
saturating_*
methods.
Floating-Point Types
Rust also has two primitive types for
floating-point numbers
, which are
numbers with decimal points. Rustâs floating-point types are
f32
and
f64
,
which are 32 bits and 64 bits in size, respectively. The default type is
f64
because on modern CPUs, itâs roughly the same speed as
f32
but is capable of
more precision. All floating-point types are signed.
Hereâs an example that shows floating-point numbers in action:
Filename: src/main.rs
fn
main
() {
let
x =
2.0
;
// f64
let
y:
f32
=
3.0
;
// f32
}
Floating-point numbers are represented according to the IEEE-754 standard.
Numeric Operations
Rust supports the basic mathematical operations youâd expect for all the number
types: addition, subtraction, multiplication, division, and remainder. Integer
division truncates toward zero to the nearest integer. The following code shows
how youâd use each numeric operation in a
let
statement:
Filename: src/main.rs
fn
main
() {
// addition
let
sum =
5
+
10
;
// subtraction
let
difference =
95.5
-
4.3
;
// multiplication
let
product =
4
*
30
;
// division
let
quotient =
56.7
/
32.2
;
let
truncated = -
5
/
3
;
// Results in -1
// remainder
let
remainder =
43
%
5
;
}
Each expression in these statements uses a mathematical operator and evaluates
to a single value, which is then bound to a variable.
Appendix
B
contains a list of all operators that Rust
provides.
The Boolean Type
As in most other programming languages, a Boolean type in Rust has two possible
values:
true
and
false
. Booleans are one byte in size. The Boolean type in
Rust is specified using
bool
. For example:
Filename: src/main.rs
fn
main
() {
let
t =
true
;
let
f:
bool
=
false
;
// with explicit type annotation
}
The main way to use Boolean values is through conditionals, such as an
if
expression. Weâll cover how
if
expressions work in Rust in the
âControl
Flowâ
section.
The Character Type
Rustâs
char
type is the languageâs most primitive alphabetic type. Here are
some examples of declaring
char
values:
Filename: src/main.rs
fn
main
() {
let
c =
'z'
;
let
z:
char
=
'â€'
;
// with explicit type annotation
let
heart_eyed_cat = 'đ»';
}
Note that we specify
char
literals with single quotation marks, as opposed to
string literals, which use double quotation marks. Rustâs
char
type is 4
bytes in size and represents a Unicode scalar value, which means it can
represent a lot more than just ASCII. Accented letters; Chinese, Japanese, and
Korean characters; emojis; and zero-width spaces are all valid
char
values in
Rust. Unicode scalar values range from
U+0000
to
U+D7FF
and
U+E000
to
U+10FFFF
inclusive. However, a âcharacterâ isnât really a concept in Unicode,
so your human intuition for what a âcharacterâ is may not match up with what a
char
is in Rust. Weâll discuss this topic in detail in
âStoring UTF-8
Encoded Text with Stringsâ
in Chapter 8.
Compound Types
Compound types
can group multiple values into one type. Rust has two
primitive compound types: tuples and arrays.
The Tuple Type
A
tuple
is a general way of grouping together a number of values with a
variety of types into one compound type. Tuples have a fixed length: Once
declared, they cannot grow or shrink in size.
We create a tuple by writing a comma-separated list of values inside
parentheses. Each position in the tuple has a type, and the types of the
different values in the tuple donât have to be the same. Weâve added optional
type annotations in this example:
Filename: src/main.rs
fn
main
() {
let
tup: (
i32
,
f64
,
u8
) = (
500
,
6.4
,
1
);
}
The variable
tup
binds to the entire tuple because a tuple is considered a
single compound element. To get the individual values out of a tuple, we can
use pattern matching to destructure a tuple value, like this:
Filename: src/main.rs
fn
main
() {
let
tup = (
500
,
6.4
,
1
);
let
(x, y, z) = tup;
println!
(
"The value of y is: {y}"
);
}
This program first creates a tuple and binds it to the variable
tup
. It then
uses a pattern with
let
to take
tup
and turn it into three separate
variables,
x
,
y
, and
z
. This is called
destructuring
because it breaks
the single tuple into three parts. Finally, the program prints the value of
y
, which is
6.4
.
We can also access a tuple element directly by using a period (
.
) followed by
the index of the value we want to access. For example:
Filename: src/main.rs
fn
main
() {
let
x: (
i32
,
f64
,
u8
) = (
500
,
6.4
,
1
);
let
five_hundred = x.
0
;
let
six_point_four = x.
1
;
let
one = x.
2
;
}
This program creates the tuple
x
and then accesses each element of the tuple
using their respective indices. As with most programming languages, the first
index in a tuple is 0.
The tuple without any values has a special name,
unit
. This value and its
corresponding type are both written
()
and represent an empty value or an
empty return type. Expressions implicitly return the unit value if they donât
return any other value.
The Array Type
Another way to have a collection of multiple values is with an
array
. Unlike
a tuple, every element of an array must have the same type. Unlike arrays in
some other languages, arrays in Rust have a fixed length.
We write the values in an array as a comma-separated list inside square
brackets:
Filename: src/main.rs
fn
main
() {
let
a = [
1
,
2
,
3
,
4
,
5
];
}
Arrays are useful when you want your data allocated on the stack, the same as
the other types we have seen so far, rather than the heap (we will discuss the
stack and the heap more in
Chapter 4
) or when
you want to ensure that you always have a fixed number of elements. An array
isnât as flexible as the vector type, though. A vector is a similar collection
type provided by the standard library that
is
allowed to grow or shrink in
size because its contents live on the heap. If youâre unsure whether to use an
array or a vector, chances are you should use a vector.
Chapter
8
discusses vectors in more detail.
However, arrays are more useful when you know the number of elements will not
need to change. For example, if you were using the names of the month in a
program, you would probably use an array rather than a vector because you know
it will always contain 12 elements:
#![allow(unused)]
fn
main
() {
let
months = [
"January"
,
"February"
,
"March"
,
"April"
,
"May"
,
"June"
,
"July"
,
"August"
,
"September"
,
"October"
,
"November"
,
"December"
];
}
You write an arrayâs type using square brackets with the type of each element,
a semicolon, and then the number of elements in the array, like so:
#![allow(unused)]
fn
main
() {
let
a: [
i32
;
5
] = [
1
,
2
,
3
,
4
,
5
];
}
Here,
i32
is the type of each element. After the semicolon, the number
5
indicates the array contains five elements.
You can also initialize an array to contain the same value for each element by
specifying the initial value, followed by a semicolon, and then the length of
the array in square brackets, as shown here:
#![allow(unused)]
fn
main
() {
let
a = [
3
;
5
];
}
The array named
a
will contain
5
elements that will all be set to the value
3
initially. This is the same as writing
let a = [3, 3, 3, 3, 3];
but in a
more concise way.
Array Element Access
An array is a single chunk of memory of a known, fixed size that can be
allocated on the stack. You can access elements of an array using indexing,
like this:
Filename: src/main.rs
fn
main
() {
let
a = [
1
,
2
,
3
,
4
,
5
];
let
first = a[
0
];
let
second = a[
1
];
}
In this example, the variable named
first
will get the value
1
because that
is the value at index
[0]
in the array. The variable named
second
will get
the value
2
from index
[1]
in the array.
Invalid Array Element Access
Letâs see what happens if you try to access an element of an array that is past
the end of the array. Say you run this code, similar to the guessing game in
Chapter 2, to get an array index from the user:
Filename: src/main.rs
use
std::io;
fn
main
() {
let
a = [
1
,
2
,
3
,
4
,
5
];
println!
(
"Please enter an array index."
);
let
mut
index =
String
::new();
io::stdin()
.read_line(&
mut
index)
.expect(
"Failed to read line"
);
let
index:
usize
= index
.trim()
.parse()
.expect(
"Index entered was not a number"
);
let
element = a[index];
println!
(
"The value of the element at index {index} is: {element}"
);
}
This code compiles successfully. If you run this code using
cargo run
and
enter
0
,
1
,
2
,
3
, or
4
, the program will print out the corresponding
value at that index in the array. If you instead enter a number past the end of
the array, such as
10
, youâll see output like this:
thread 'main' panicked at src/main.rs:19:19:
index out of bounds: the len is 5 but the index is 10
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
The program resulted in a runtime error at the point of using an invalid
value in the indexing operation. The program exited with an error message and
didnât execute the final
println!
statement. When you attempt to access an
element using indexing, Rust will check that the index youâve specified is less
than the array length. If the index is greater than or equal to the length,
Rust will panic. This check has to happen at runtime, especially in this case,
because the compiler canât possibly know what value a user will enter when they
run the code later.
This is an example of Rustâs memory safety principles in action. In many
low-level languages, this kind of check is not done, and when you provide an
incorrect index, invalid memory can be accessed. Rust protects you against this
kind of error by immediately exiting instead of allowing the memory access and
continuing. Chapter 9 discusses more of Rustâs error handling and how you can
write readable, safe code that neither panics nor allows invalid memory access. |
| Markdown | ## Keyboard shortcuts
Press `â` or `â` to navigate between chapters
Press `S` or `/` to search in the book
Press `?` to show this help
Press `Esc` to hide this help
1. [The Rust Programming Language](https://doc.rust-lang.org/book/title-page.html)
2. [Foreword](https://doc.rust-lang.org/book/foreword.html)
3. [Introduction](https://doc.rust-lang.org/book/ch00-00-introduction.html)
4. [**1\.** Getting Started](https://doc.rust-lang.org/book/ch01-00-getting-started.html)
1. [**1\.1.** Installation](https://doc.rust-lang.org/book/ch01-01-installation.html)
2. [**1\.2.** Hello, World\!](https://doc.rust-lang.org/book/ch01-02-hello-world.html)
3. [**1\.3.** Hello, Cargo\!](https://doc.rust-lang.org/book/ch01-03-hello-cargo.html)
5. [**2\.** Programming a Guessing Game](https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html)
6. [**3\.** Common Programming Concepts](https://doc.rust-lang.org/book/ch03-00-common-programming-concepts.html)
1. [**3\.1.** Variables and Mutability](https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html)
2. [**3\.2.** Data Types](https://doc.rust-lang.org/book/ch03-02-data-types.html)
1. [Data Types](https://doc.rust-lang.org/book/ch03-02-data-types.html#data-types)
1. [Scalar Types](https://doc.rust-lang.org/book/ch03-02-data-types.html#scalar-types)
[â±]()
1. [Integer Types](https://doc.rust-lang.org/book/ch03-02-data-types.html#integer-types)
[â±]()
1. [Integer Overflow](https://doc.rust-lang.org/book/ch03-02-data-types.html#integer-overflow)
2. [Floating-Point Types](https://doc.rust-lang.org/book/ch03-02-data-types.html#floating-point-types)
3. [Numeric Operations](https://doc.rust-lang.org/book/ch03-02-data-types.html#numeric-operations)
4. [The Boolean Type](https://doc.rust-lang.org/book/ch03-02-data-types.html#the-boolean-type)
5. [The Character Type](https://doc.rust-lang.org/book/ch03-02-data-types.html#the-character-type)
2. [Compound Types](https://doc.rust-lang.org/book/ch03-02-data-types.html#compound-types)
[â±]()
1. [The Tuple Type](https://doc.rust-lang.org/book/ch03-02-data-types.html#the-tuple-type)
2. [The Array Type](https://doc.rust-lang.org/book/ch03-02-data-types.html#the-array-type)
3. [Array Element Access](https://doc.rust-lang.org/book/ch03-02-data-types.html#array-element-access)
4. [Invalid Array Element Access](https://doc.rust-lang.org/book/ch03-02-data-types.html#invalid-array-element-access)
3. [**3\.3.** Functions](https://doc.rust-lang.org/book/ch03-03-how-functions-work.html)
4. [**3\.4.** Comments](https://doc.rust-lang.org/book/ch03-04-comments.html)
5. [**3\.5.** Control Flow](https://doc.rust-lang.org/book/ch03-05-control-flow.html)
7. [**4\.** Understanding Ownership](https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html)
1. [**4\.1.** What is Ownership?](https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html)
2. [**4\.2.** References and Borrowing](https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html)
3. [**4\.3.** The Slice Type](https://doc.rust-lang.org/book/ch04-03-slices.html)
8. [**5\.** Using Structs to Structure Related Data](https://doc.rust-lang.org/book/ch05-00-structs.html)
1. [**5\.1.** Defining and Instantiating Structs](https://doc.rust-lang.org/book/ch05-01-defining-structs.html)
2. [**5\.2.** An Example Program Using Structs](https://doc.rust-lang.org/book/ch05-02-example-structs.html)
3. [**5\.3.** Methods](https://doc.rust-lang.org/book/ch05-03-method-syntax.html)
9. [**6\.** Enums and Pattern Matching](https://doc.rust-lang.org/book/ch06-00-enums.html)
1. [**6\.1.** Defining an Enum](https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html)
2. [**6\.2.** The match Control Flow Construct](https://doc.rust-lang.org/book/ch06-02-match.html)
3. [**6\.3.** Concise Control Flow with if let and let...else](https://doc.rust-lang.org/book/ch06-03-if-let.html)
10. [**7\.** Packages, Crates, and Modules](https://doc.rust-lang.org/book/ch07-00-managing-growing-projects-with-packages-crates-and-modules.html)
1. [**7\.1.** Packages and Crates](https://doc.rust-lang.org/book/ch07-01-packages-and-crates.html)
2. [**7\.2.** Control Scope and Privacy with Modules](https://doc.rust-lang.org/book/ch07-02-defining-modules-to-control-scope-and-privacy.html)
3. [**7\.3.** Paths for Referring to an Item in the Module Tree](https://doc.rust-lang.org/book/ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html)
4. [**7\.4.** Bringing Paths Into Scope with the use Keyword](https://doc.rust-lang.org/book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.html)
5. [**7\.5.** Separating Modules into Different Files](https://doc.rust-lang.org/book/ch07-05-separating-modules-into-different-files.html)
11. [**8\.** Common Collections](https://doc.rust-lang.org/book/ch08-00-common-collections.html)
1. [**8\.1.** Storing Lists of Values with Vectors](https://doc.rust-lang.org/book/ch08-01-vectors.html)
2. [**8\.2.** Storing UTF-8 Encoded Text with Strings](https://doc.rust-lang.org/book/ch08-02-strings.html)
3. [**8\.3.** Storing Keys with Associated Values in Hash Maps](https://doc.rust-lang.org/book/ch08-03-hash-maps.html)
12. [**9\.** Error Handling](https://doc.rust-lang.org/book/ch09-00-error-handling.html)
1. [**9\.1.** Unrecoverable Errors with panic\!](https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html)
2. [**9\.2.** Recoverable Errors with Result](https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html)
3. [**9\.3.** To panic! or Not to panic\!](https://doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html)
13. [**10\.** Generic Types, Traits, and Lifetimes](https://doc.rust-lang.org/book/ch10-00-generics.html)
1. [**10\.1.** Generic Data Types](https://doc.rust-lang.org/book/ch10-01-syntax.html)
2. [**10\.2.** Defining Shared Behavior with Traits](https://doc.rust-lang.org/book/ch10-02-traits.html)
3. [**10\.3.** Validating References with Lifetimes](https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html)
14. [**11\.** Writing Automated Tests](https://doc.rust-lang.org/book/ch11-00-testing.html)
1. [**11\.1.** How to Write Tests](https://doc.rust-lang.org/book/ch11-01-writing-tests.html)
2. [**11\.2.** Controlling How Tests Are Run](https://doc.rust-lang.org/book/ch11-02-running-tests.html)
3. [**11\.3.** Test Organization](https://doc.rust-lang.org/book/ch11-03-test-organization.html)
15. [**12\.** An I/O Project: Building a Command Line Program](https://doc.rust-lang.org/book/ch12-00-an-io-project.html)
1. [**12\.1.** Accepting Command Line Arguments](https://doc.rust-lang.org/book/ch12-01-accepting-command-line-arguments.html)
2. [**12\.2.** Reading a File](https://doc.rust-lang.org/book/ch12-02-reading-a-file.html)
3. [**12\.3.** Refactoring to Improve Modularity and Error Handling](https://doc.rust-lang.org/book/ch12-03-improving-error-handling-and-modularity.html)
4. [**12\.4.** Adding Functionality with Test Driven Development](https://doc.rust-lang.org/book/ch12-04-testing-the-librarys-functionality.html)
5. [**12\.5.** Working with Environment Variables](https://doc.rust-lang.org/book/ch12-05-working-with-environment-variables.html)
6. [**12\.6.** Redirecting Errors to Standard Error](https://doc.rust-lang.org/book/ch12-06-writing-to-stderr-instead-of-stdout.html)
16. [**13\.** Functional Language Features: Iterators and Closures](https://doc.rust-lang.org/book/ch13-00-functional-features.html)
1. [**13\.1.** Closures](https://doc.rust-lang.org/book/ch13-01-closures.html)
2. [**13\.2.** Processing a Series of Items with Iterators](https://doc.rust-lang.org/book/ch13-02-iterators.html)
3. [**13\.3.** Improving Our I/O Project](https://doc.rust-lang.org/book/ch13-03-improving-our-io-project.html)
4. [**13\.4.** Performance in Loops vs. Iterators](https://doc.rust-lang.org/book/ch13-04-performance.html)
17. [**14\.** More about Cargo and Crates.io](https://doc.rust-lang.org/book/ch14-00-more-about-cargo.html)
1. [**14\.1.** Customizing Builds with Release Profiles](https://doc.rust-lang.org/book/ch14-01-release-profiles.html)
2. [**14\.2.** Publishing a Crate to Crates.io](https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html)
3. [**14\.3.** Cargo Workspaces](https://doc.rust-lang.org/book/ch14-03-cargo-workspaces.html)
4. [**14\.4.** Installing Binaries with cargo install](https://doc.rust-lang.org/book/ch14-04-installing-binaries.html)
5. [**14\.5.** Extending Cargo with Custom Commands](https://doc.rust-lang.org/book/ch14-05-extending-cargo.html)
18. [**15\.** Smart Pointers](https://doc.rust-lang.org/book/ch15-00-smart-pointers.html)
1. [**15\.1.** Using Box\<T\> to Point to Data on the Heap](https://doc.rust-lang.org/book/ch15-01-box.html)
2. [**15\.2.** Treating Smart Pointers Like Regular References](https://doc.rust-lang.org/book/ch15-02-deref.html)
3. [**15\.3.** Running Code on Cleanup with the Drop Trait](https://doc.rust-lang.org/book/ch15-03-drop.html)
4. [**15\.4.** Rc\<T\>, the Reference Counted Smart Pointer](https://doc.rust-lang.org/book/ch15-04-rc.html)
5. [**15\.5.** RefCell\<T\> and the Interior Mutability Pattern](https://doc.rust-lang.org/book/ch15-05-interior-mutability.html)
6. [**15\.6.** Reference Cycles Can Leak Memory](https://doc.rust-lang.org/book/ch15-06-reference-cycles.html)
19. [**16\.** Fearless Concurrency](https://doc.rust-lang.org/book/ch16-00-concurrency.html)
1. [**16\.1.** Using Threads to Run Code Simultaneously](https://doc.rust-lang.org/book/ch16-01-threads.html)
2. [**16\.2.** Transfer Data Between Threads with Message Passing](https://doc.rust-lang.org/book/ch16-02-message-passing.html)
3. [**16\.3.** Shared-State Concurrency](https://doc.rust-lang.org/book/ch16-03-shared-state.html)
4. [**16\.4.** Extensible Concurrency with Send and Sync](https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html)
20. [**17\.** Fundamentals of Asynchronous Programming: Async, Await, Futures, and Streams](https://doc.rust-lang.org/book/ch17-00-async-await.html)
1. [**17\.1.** Futures and the Async Syntax](https://doc.rust-lang.org/book/ch17-01-futures-and-syntax.html)
2. [**17\.2.** Applying Concurrency with Async](https://doc.rust-lang.org/book/ch17-02-concurrency-with-async.html)
3. [**17\.3.** Working With Any Number of Futures](https://doc.rust-lang.org/book/ch17-03-more-futures.html)
4. [**17\.4.** Streams: Futures in Sequence](https://doc.rust-lang.org/book/ch17-04-streams.html)
5. [**17\.5.** A Closer Look at the Traits for Async](https://doc.rust-lang.org/book/ch17-05-traits-for-async.html)
6. [**17\.6.** Futures, Tasks, and Threads](https://doc.rust-lang.org/book/ch17-06-futures-tasks-threads.html)
21. [**18\.** Object Oriented Programming Features](https://doc.rust-lang.org/book/ch18-00-oop.html)
1. [**18\.1.** Characteristics of Object-Oriented Languages](https://doc.rust-lang.org/book/ch18-01-what-is-oo.html)
2. [**18\.2.** Using Trait Objects to Abstract over Shared Behavior](https://doc.rust-lang.org/book/ch18-02-trait-objects.html)
3. [**18\.3.** Implementing an Object-Oriented Design Pattern](https://doc.rust-lang.org/book/ch18-03-oo-design-patterns.html)
22. [**19\.** Patterns and Matching](https://doc.rust-lang.org/book/ch19-00-patterns.html)
1. [**19\.1.** All the Places Patterns Can Be Used](https://doc.rust-lang.org/book/ch19-01-all-the-places-for-patterns.html)
2. [**19\.2.** Refutability: Whether a Pattern Might Fail to Match](https://doc.rust-lang.org/book/ch19-02-refutability.html)
3. [**19\.3.** Pattern Syntax](https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html)
23. [**20\.** Advanced Features](https://doc.rust-lang.org/book/ch20-00-advanced-features.html)
1. [**20\.1.** Unsafe Rust](https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html)
2. [**20\.2.** Advanced Traits](https://doc.rust-lang.org/book/ch20-02-advanced-traits.html)
3. [**20\.3.** Advanced Types](https://doc.rust-lang.org/book/ch20-03-advanced-types.html)
4. [**20\.4.** Advanced Functions and Closures](https://doc.rust-lang.org/book/ch20-04-advanced-functions-and-closures.html)
5. [**20\.5.** Macros](https://doc.rust-lang.org/book/ch20-05-macros.html)
24. [**21\.** Final Project: Building a Multithreaded Web Server](https://doc.rust-lang.org/book/ch21-00-final-project-a-web-server.html)
1. [**21\.1.** Building a Single-Threaded Web Server](https://doc.rust-lang.org/book/ch21-01-single-threaded.html)
2. [**21\.2.** From Single-Threaded to Multithreaded Server](https://doc.rust-lang.org/book/ch21-02-multithreaded.html)
3. [**21\.3.** Graceful Shutdown and Cleanup](https://doc.rust-lang.org/book/ch21-03-graceful-shutdown-and-cleanup.html)
25. [**22\.** Appendix](https://doc.rust-lang.org/book/appendix-00.html)
1. [**22\.1.** A - Keywords](https://doc.rust-lang.org/book/appendix-01-keywords.html)
2. [**22\.2.** B - Operators and Symbols](https://doc.rust-lang.org/book/appendix-02-operators.html)
3. [**22\.3.** C - Derivable Traits](https://doc.rust-lang.org/book/appendix-03-derivable-traits.html)
4. [**22\.4.** D - Useful Development Tools](https://doc.rust-lang.org/book/appendix-04-useful-development-tools.html)
5. [**22\.5.** E - Editions](https://doc.rust-lang.org/book/appendix-05-editions.html)
6. [**22\.6.** F - Translations of the Book](https://doc.rust-lang.org/book/appendix-06-translation.html)
7. [**22\.7.** G - How Rust is Made and âNightly Rustâ](https://doc.rust-lang.org/book/appendix-07-nightly-rust.html)
- Auto
- Light
- Rust
- Coal
- Navy
- Ayu
# The Rust Programming Language
## [Data Types](https://doc.rust-lang.org/book/ch03-02-data-types.html#data-types)
Every value in Rust is of a certain *data type*, which tells Rust what kind of data is being specified so that it knows how to work with that data. Weâll look at two data type subsets: scalar and compound.
Keep in mind that Rust is a *statically typed* language, which means that it must know the types of all variables at compile time. The compiler can usually infer what type we want to use based on the value and how we use it. In cases when many types are possible, such as when we converted a `String` to a numeric type using `parse` in the [âComparing the Guess to the Secret Numberâ](https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#comparing-the-guess-to-the-secret-number) section in Chapter 2, we must add a type annotation, like this:
```
```
If we donât add the `: u32` type annotation shown in the preceding code, Rust will display the following error, which means the compiler needs more information from us to know which type we want to use:
```
```
Youâll see different type annotations for other data types.
### [Scalar Types](https://doc.rust-lang.org/book/ch03-02-data-types.html#scalar-types)
A *scalar* type represents a single value. Rust has four primary scalar types: integers, floating-point numbers, Booleans, and characters. You may recognize these from other programming languages. Letâs jump into how they work in Rust.
#### [Integer Types](https://doc.rust-lang.org/book/ch03-02-data-types.html#integer-types)
An *integer* is a number without a fractional component. We used one integer type in Chapter 2, the `u32` type. This type declaration indicates that the value itâs associated with should be an unsigned integer (signed integer types start with `i` instead of `u`) that takes up 32 bits of space. Table 3-1 shows the built-in integer types in Rust. We can use any of these variants to declare the type of an integer value.
Table 3-1: Integer Types in Rust
| Length | Signed | Unsigned |
|---|---|---|
| 8-bit | `i8` | `u8` |
| 16-bit | `i16` | `u16` |
| 32-bit | `i32` | `u32` |
| 64-bit | `i64` | `u64` |
| 128-bit | `i128` | `u128` |
| Architecture-dependent | `isize` | `usize` |
Each variant can be either signed or unsigned and has an explicit size. *Signed* and *unsigned* refer to whether itâs possible for the number to be negativeâin other words, whether the number needs to have a sign with it (signed) or whether it will only ever be positive and can therefore be represented without a sign (unsigned). Itâs like writing numbers on paper: When the sign matters, a number is shown with a plus sign or a minus sign; however, when itâs safe to assume the number is positive, itâs shown with no sign. Signed numbers are stored using [twoâs complement](https://en.wikipedia.org/wiki/Two%27s_complement) representation.
Each signed variant can store numbers from â(2n â 1) to 2n â 1 â 1 inclusive, where *n* is the number of bits that variant uses. So, an `i8` can store numbers from â(27) to 27 â 1, which equals â128 to 127. Unsigned variants can store numbers from 0 to 2n â 1, so a `u8` can store numbers from 0 to 28 â 1, which equals 0 to 255.
Additionally, the `isize` and `usize` types depend on the architecture of the computer your program is running on: 64 bits if youâre on a 64-bit architecture and 32 bits if youâre on a 32-bit architecture.
You can write integer literals in any of the forms shown in Table 3-2. Note that number literals that can be multiple numeric types allow a type suffix, such as `57u8`, to designate the type. Number literals can also use `_` as a visual separator to make the number easier to read, such as `1_000`, which will have the same value as if you had specified `1000`.
Table 3-2: Integer Literals in Rust
| Number literals | Example |
|---|---|
| Decimal | `98_222` |
| Hex | `0xff` |
| Octal | `0o77` |
| Binary | `0b1111_0000` |
| Byte (`u8` only) | `b'A'` |
So how do you know which type of integer to use? If youâre unsure, Rustâs defaults are generally good places to start: Integer types default to `i32`. The primary situation in which youâd use `isize` or `usize` is when indexing some sort of collection.
##### [Integer Overflow](https://doc.rust-lang.org/book/ch03-02-data-types.html#integer-overflow)
Letâs say you have a variable of type `u8` that can hold values between 0 and 255. If you try to change the variable to a value outside that range, such as 256, *integer overflow* will occur, which can result in one of two behaviors. When youâre compiling in debug mode, Rust includes checks for integer overflow that cause your program to *panic* at runtime if this behavior occurs. Rust uses the term *panicking* when a program exits with an error; weâll discuss panics in more depth in the [âUnrecoverable Errors with `panic!`â](https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html) section in Chapter 9.
When youâre compiling in release mode with the `--release` flag, Rust does *not* include checks for integer overflow that cause panics. Instead, if overflow occurs, Rust performs *twoâs complement wrapping*. In short, values greater than the maximum value the type can hold âwrap aroundâ to the minimum of the values the type can hold. In the case of a `u8`, the value 256 becomes 0, the value 257 becomes 1, and so on. The program wonât panic, but the variable will have a value that probably isnât what you were expecting it to have. Relying on integer overflowâs wrapping behavior is considered an error.
To explicitly handle the possibility of overflow, you can use these families of methods provided by the standard library for primitive numeric types:
- Wrap in all modes with the `wrapping_*` methods, such as `wrapping_add`.
- Return the `None` value if there is overflow with the `checked_*` methods.
- Return the value and a Boolean indicating whether there was overflow with the `overflowing_*` methods.
- Saturate at the valueâs minimum or maximum values with the `saturating_*` methods.
#### [Floating-Point Types](https://doc.rust-lang.org/book/ch03-02-data-types.html#floating-point-types)
Rust also has two primitive types for *floating-point numbers*, which are numbers with decimal points. Rustâs floating-point types are `f32` and `f64`, which are 32 bits and 64 bits in size, respectively. The default type is `f64` because on modern CPUs, itâs roughly the same speed as `f32` but is capable of more precision. All floating-point types are signed.
Hereâs an example that shows floating-point numbers in action:
Filename: src/main.rs
```
```
Floating-point numbers are represented according to the IEEE-754 standard.
#### [Numeric Operations](https://doc.rust-lang.org/book/ch03-02-data-types.html#numeric-operations)
Rust supports the basic mathematical operations youâd expect for all the number types: addition, subtraction, multiplication, division, and remainder. Integer division truncates toward zero to the nearest integer. The following code shows how youâd use each numeric operation in a `let` statement:
Filename: src/main.rs
```
```
Each expression in these statements uses a mathematical operator and evaluates to a single value, which is then bound to a variable. [Appendix B](https://doc.rust-lang.org/book/appendix-02-operators.html) contains a list of all operators that Rust provides.
#### [The Boolean Type](https://doc.rust-lang.org/book/ch03-02-data-types.html#the-boolean-type)
As in most other programming languages, a Boolean type in Rust has two possible values: `true` and `false`. Booleans are one byte in size. The Boolean type in Rust is specified using `bool`. For example:
Filename: src/main.rs
```
```
The main way to use Boolean values is through conditionals, such as an `if` expression. Weâll cover how `if` expressions work in Rust in the [âControl Flowâ](https://doc.rust-lang.org/book/ch03-05-control-flow.html#control-flow) section.
#### [The Character Type](https://doc.rust-lang.org/book/ch03-02-data-types.html#the-character-type)
Rustâs `char` type is the languageâs most primitive alphabetic type. Here are some examples of declaring `char` values:
Filename: src/main.rs
```
```
Note that we specify `char` literals with single quotation marks, as opposed to string literals, which use double quotation marks. Rustâs `char` type is 4 bytes in size and represents a Unicode scalar value, which means it can represent a lot more than just ASCII. Accented letters; Chinese, Japanese, and Korean characters; emojis; and zero-width spaces are all valid `char` values in Rust. Unicode scalar values range from `U+0000` to `U+D7FF` and `U+E000` to `U+10FFFF` inclusive. However, a âcharacterâ isnât really a concept in Unicode, so your human intuition for what a âcharacterâ is may not match up with what a `char` is in Rust. Weâll discuss this topic in detail in [âStoring UTF-8 Encoded Text with Stringsâ](https://doc.rust-lang.org/book/ch08-02-strings.html#storing-utf-8-encoded-text-with-strings) in Chapter 8.
### [Compound Types](https://doc.rust-lang.org/book/ch03-02-data-types.html#compound-types)
*Compound types* can group multiple values into one type. Rust has two primitive compound types: tuples and arrays.
#### [The Tuple Type](https://doc.rust-lang.org/book/ch03-02-data-types.html#the-tuple-type)
A *tuple* is a general way of grouping together a number of values with a variety of types into one compound type. Tuples have a fixed length: Once declared, they cannot grow or shrink in size.
We create a tuple by writing a comma-separated list of values inside parentheses. Each position in the tuple has a type, and the types of the different values in the tuple donât have to be the same. Weâve added optional type annotations in this example:
Filename: src/main.rs
```
```
The variable `tup` binds to the entire tuple because a tuple is considered a single compound element. To get the individual values out of a tuple, we can use pattern matching to destructure a tuple value, like this:
Filename: src/main.rs
```
```
This program first creates a tuple and binds it to the variable `tup`. It then uses a pattern with `let` to take `tup` and turn it into three separate variables, `x`, `y`, and `z`. This is called *destructuring* because it breaks the single tuple into three parts. Finally, the program prints the value of `y`, which is `6.4`.
We can also access a tuple element directly by using a period (`.`) followed by the index of the value we want to access. For example:
Filename: src/main.rs
```
```
This program creates the tuple `x` and then accesses each element of the tuple using their respective indices. As with most programming languages, the first index in a tuple is 0.
The tuple without any values has a special name, *unit*. This value and its corresponding type are both written `()` and represent an empty value or an empty return type. Expressions implicitly return the unit value if they donât return any other value.
#### [The Array Type](https://doc.rust-lang.org/book/ch03-02-data-types.html#the-array-type)
Another way to have a collection of multiple values is with an *array*. Unlike a tuple, every element of an array must have the same type. Unlike arrays in some other languages, arrays in Rust have a fixed length.
We write the values in an array as a comma-separated list inside square brackets:
Filename: src/main.rs
```
```
Arrays are useful when you want your data allocated on the stack, the same as the other types we have seen so far, rather than the heap (we will discuss the stack and the heap more in [Chapter 4](https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#the-stack-and-the-heap)) or when you want to ensure that you always have a fixed number of elements. An array isnât as flexible as the vector type, though. A vector is a similar collection type provided by the standard library that *is* allowed to grow or shrink in size because its contents live on the heap. If youâre unsure whether to use an array or a vector, chances are you should use a vector. [Chapter 8](https://doc.rust-lang.org/book/ch08-01-vectors.html) discusses vectors in more detail.
However, arrays are more useful when you know the number of elements will not need to change. For example, if you were using the names of the month in a program, you would probably use an array rather than a vector because you know it will always contain 12 elements:
```
```
You write an arrayâs type using square brackets with the type of each element, a semicolon, and then the number of elements in the array, like so:
```
```
Here, `i32` is the type of each element. After the semicolon, the number `5` indicates the array contains five elements.
You can also initialize an array to contain the same value for each element by specifying the initial value, followed by a semicolon, and then the length of the array in square brackets, as shown here:
```
```
The array named `a` will contain `5` elements that will all be set to the value `3` initially. This is the same as writing `let a = [3, 3, 3, 3, 3];` but in a more concise way.
#### [Array Element Access](https://doc.rust-lang.org/book/ch03-02-data-types.html#array-element-access)
An array is a single chunk of memory of a known, fixed size that can be allocated on the stack. You can access elements of an array using indexing, like this:
Filename: src/main.rs
```
```
In this example, the variable named `first` will get the value `1` because that is the value at index `[0]` in the array. The variable named `second` will get the value `2` from index `[1]` in the array.
#### [Invalid Array Element Access](https://doc.rust-lang.org/book/ch03-02-data-types.html#invalid-array-element-access)
Letâs see what happens if you try to access an element of an array that is past the end of the array. Say you run this code, similar to the guessing game in Chapter 2, to get an array index from the user:
Filename: src/main.rs
```
```
This code compiles successfully. If you run this code using `cargo run` and enter `0`, `1`, `2`, `3`, or `4`, the program will print out the corresponding value at that index in the array. If you instead enter a number past the end of the array, such as `10`, youâll see output like this:
```
```
The program resulted in a runtime error at the point of using an invalid value in the indexing operation. The program exited with an error message and didnât execute the final `println!` statement. When you attempt to access an element using indexing, Rust will check that the index youâve specified is less than the array length. If the index is greater than or equal to the length, Rust will panic. This check has to happen at runtime, especially in this case, because the compiler canât possibly know what value a user will enter when they run the code later.
This is an example of Rustâs memory safety principles in action. In many low-level languages, this kind of check is not done, and when you provide an incorrect index, invalid memory can be accessed. Rust protects you against this kind of error by immediately exiting instead of allowing the memory access and continuing. Chapter 9 discusses more of Rustâs error handling and how you can write readable, safe code that neither panics nor allows invalid memory access. |
| Readable Markdown | Every value in Rust is of a certain *data type*, which tells Rust what kind of data is being specified so that it knows how to work with that data. Weâll look at two data type subsets: scalar and compound.
Keep in mind that Rust is a *statically typed* language, which means that it must know the types of all variables at compile time. The compiler can usually infer what type we want to use based on the value and how we use it. In cases when many types are possible, such as when we converted a `String` to a numeric type using `parse` in the [âComparing the Guess to the Secret Numberâ](https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#comparing-the-guess-to-the-secret-number) section in Chapter 2, we must add a type annotation, like this:
```
#![allow(unused)]
fn main() {
let guess: u32 = "42".parse().expect("Not a number!");
}
```
If we donât add the `: u32` type annotation shown in the preceding code, Rust will display the following error, which means the compiler needs more information from us to know which type we want to use:
```
$ cargo build
Compiling no_type_annotations v0.1.0 (file:///projects/no_type_annotations)
error[E0284]: type annotations needed
--> src/main.rs:2:9
|
2 | let guess = "42".parse().expect("Not a number!");
| ^^^^^ ----- type must be known at this point
|
= note: cannot satisfy `<_ as FromStr>::Err == _`
help: consider giving `guess` an explicit type
|
2 | let guess: /* Type */ = "42".parse().expect("Not a number!");
| ++++++++++++
For more information about this error, try `rustc --explain E0284`.
error: could not compile `no_type_annotations` (bin "no_type_annotations") due to 1 previous error
```
Youâll see different type annotations for other data types.
### [Scalar Types](https://doc.rust-lang.org/book/ch03-02-data-types.html#scalar-types)
A *scalar* type represents a single value. Rust has four primary scalar types: integers, floating-point numbers, Booleans, and characters. You may recognize these from other programming languages. Letâs jump into how they work in Rust.
#### [Integer Types](https://doc.rust-lang.org/book/ch03-02-data-types.html#integer-types)
An *integer* is a number without a fractional component. We used one integer type in Chapter 2, the `u32` type. This type declaration indicates that the value itâs associated with should be an unsigned integer (signed integer types start with `i` instead of `u`) that takes up 32 bits of space. Table 3-1 shows the built-in integer types in Rust. We can use any of these variants to declare the type of an integer value.
Table 3-1: Integer Types in Rust
| Length | Signed | Unsigned |
|---|---|---|
| 8-bit | `i8` | `u8` |
| 16-bit | `i16` | `u16` |
| 32-bit | `i32` | `u32` |
| 64-bit | `i64` | `u64` |
| 128-bit | `i128` | `u128` |
| Architecture-dependent | `isize` | `usize` |
Each variant can be either signed or unsigned and has an explicit size. *Signed* and *unsigned* refer to whether itâs possible for the number to be negativeâin other words, whether the number needs to have a sign with it (signed) or whether it will only ever be positive and can therefore be represented without a sign (unsigned). Itâs like writing numbers on paper: When the sign matters, a number is shown with a plus sign or a minus sign; however, when itâs safe to assume the number is positive, itâs shown with no sign. Signed numbers are stored using [twoâs complement](https://en.wikipedia.org/wiki/Two%27s_complement) representation.
Each signed variant can store numbers from â(2n â 1) to 2n â 1 â 1 inclusive, where *n* is the number of bits that variant uses. So, an `i8` can store numbers from â(27) to 27 â 1, which equals â128 to 127. Unsigned variants can store numbers from 0 to 2n â 1, so a `u8` can store numbers from 0 to 28 â 1, which equals 0 to 255.
Additionally, the `isize` and `usize` types depend on the architecture of the computer your program is running on: 64 bits if youâre on a 64-bit architecture and 32 bits if youâre on a 32-bit architecture.
You can write integer literals in any of the forms shown in Table 3-2. Note that number literals that can be multiple numeric types allow a type suffix, such as `57u8`, to designate the type. Number literals can also use `_` as a visual separator to make the number easier to read, such as `1_000`, which will have the same value as if you had specified `1000`.
Table 3-2: Integer Literals in Rust
| Number literals | Example |
|---|---|
| Decimal | `98_222` |
| Hex | `0xff` |
| Octal | `0o77` |
| Binary | `0b1111_0000` |
| Byte (`u8` only) | `b'A'` |
So how do you know which type of integer to use? If youâre unsure, Rustâs defaults are generally good places to start: Integer types default to `i32`. The primary situation in which youâd use `isize` or `usize` is when indexing some sort of collection.
##### [Integer Overflow](https://doc.rust-lang.org/book/ch03-02-data-types.html#integer-overflow)
Letâs say you have a variable of type `u8` that can hold values between 0 and 255. If you try to change the variable to a value outside that range, such as 256, *integer overflow* will occur, which can result in one of two behaviors. When youâre compiling in debug mode, Rust includes checks for integer overflow that cause your program to *panic* at runtime if this behavior occurs. Rust uses the term *panicking* when a program exits with an error; weâll discuss panics in more depth in the [âUnrecoverable Errors with `panic!`â](https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html) section in Chapter 9.
When youâre compiling in release mode with the `--release` flag, Rust does *not* include checks for integer overflow that cause panics. Instead, if overflow occurs, Rust performs *twoâs complement wrapping*. In short, values greater than the maximum value the type can hold âwrap aroundâ to the minimum of the values the type can hold. In the case of a `u8`, the value 256 becomes 0, the value 257 becomes 1, and so on. The program wonât panic, but the variable will have a value that probably isnât what you were expecting it to have. Relying on integer overflowâs wrapping behavior is considered an error.
To explicitly handle the possibility of overflow, you can use these families of methods provided by the standard library for primitive numeric types:
- Wrap in all modes with the `wrapping_*` methods, such as `wrapping_add`.
- Return the `None` value if there is overflow with the `checked_*` methods.
- Return the value and a Boolean indicating whether there was overflow with the `overflowing_*` methods.
- Saturate at the valueâs minimum or maximum values with the `saturating_*` methods.
#### [Floating-Point Types](https://doc.rust-lang.org/book/ch03-02-data-types.html#floating-point-types)
Rust also has two primitive types for *floating-point numbers*, which are numbers with decimal points. Rustâs floating-point types are `f32` and `f64`, which are 32 bits and 64 bits in size, respectively. The default type is `f64` because on modern CPUs, itâs roughly the same speed as `f32` but is capable of more precision. All floating-point types are signed.
Hereâs an example that shows floating-point numbers in action:
Filename: src/main.rs
```
fn main() {
let x = 2.0; // f64
let y: f32 = 3.0; // f32
}
```
Floating-point numbers are represented according to the IEEE-754 standard.
#### [Numeric Operations](https://doc.rust-lang.org/book/ch03-02-data-types.html#numeric-operations)
Rust supports the basic mathematical operations youâd expect for all the number types: addition, subtraction, multiplication, division, and remainder. Integer division truncates toward zero to the nearest integer. The following code shows how youâd use each numeric operation in a `let` statement:
Filename: src/main.rs
```
fn main() {
// addition
let sum = 5 + 10;
// subtraction
let difference = 95.5 - 4.3;
// multiplication
let product = 4 * 30;
// division
let quotient = 56.7 / 32.2;
let truncated = -5 / 3; // Results in -1
// remainder
let remainder = 43 % 5;
}
```
Each expression in these statements uses a mathematical operator and evaluates to a single value, which is then bound to a variable. [Appendix B](https://doc.rust-lang.org/book/appendix-02-operators.html) contains a list of all operators that Rust provides.
#### [The Boolean Type](https://doc.rust-lang.org/book/ch03-02-data-types.html#the-boolean-type)
As in most other programming languages, a Boolean type in Rust has two possible values: `true` and `false`. Booleans are one byte in size. The Boolean type in Rust is specified using `bool`. For example:
Filename: src/main.rs
```
fn main() {
let t = true;
let f: bool = false; // with explicit type annotation
}
```
The main way to use Boolean values is through conditionals, such as an `if` expression. Weâll cover how `if` expressions work in Rust in the [âControl Flowâ](https://doc.rust-lang.org/book/ch03-05-control-flow.html#control-flow) section.
#### [The Character Type](https://doc.rust-lang.org/book/ch03-02-data-types.html#the-character-type)
Rustâs `char` type is the languageâs most primitive alphabetic type. Here are some examples of declaring `char` values:
Filename: src/main.rs
```
fn main() {
let c = 'z';
let z: char = 'â€'; // with explicit type annotation
let heart_eyed_cat = 'đ»';
}
```
Note that we specify `char` literals with single quotation marks, as opposed to string literals, which use double quotation marks. Rustâs `char` type is 4 bytes in size and represents a Unicode scalar value, which means it can represent a lot more than just ASCII. Accented letters; Chinese, Japanese, and Korean characters; emojis; and zero-width spaces are all valid `char` values in Rust. Unicode scalar values range from `U+0000` to `U+D7FF` and `U+E000` to `U+10FFFF` inclusive. However, a âcharacterâ isnât really a concept in Unicode, so your human intuition for what a âcharacterâ is may not match up with what a `char` is in Rust. Weâll discuss this topic in detail in [âStoring UTF-8 Encoded Text with Stringsâ](https://doc.rust-lang.org/book/ch08-02-strings.html#storing-utf-8-encoded-text-with-strings) in Chapter 8.
### [Compound Types](https://doc.rust-lang.org/book/ch03-02-data-types.html#compound-types)
*Compound types* can group multiple values into one type. Rust has two primitive compound types: tuples and arrays.
#### [The Tuple Type](https://doc.rust-lang.org/book/ch03-02-data-types.html#the-tuple-type)
A *tuple* is a general way of grouping together a number of values with a variety of types into one compound type. Tuples have a fixed length: Once declared, they cannot grow or shrink in size.
We create a tuple by writing a comma-separated list of values inside parentheses. Each position in the tuple has a type, and the types of the different values in the tuple donât have to be the same. Weâve added optional type annotations in this example:
Filename: src/main.rs
```
fn main() {
let tup: (i32, f64, u8) = (500, 6.4, 1);
}
```
The variable `tup` binds to the entire tuple because a tuple is considered a single compound element. To get the individual values out of a tuple, we can use pattern matching to destructure a tuple value, like this:
Filename: src/main.rs
```
fn main() {
let tup = (500, 6.4, 1);
let (x, y, z) = tup;
println!("The value of y is: {y}");
}
```
This program first creates a tuple and binds it to the variable `tup`. It then uses a pattern with `let` to take `tup` and turn it into three separate variables, `x`, `y`, and `z`. This is called *destructuring* because it breaks the single tuple into three parts. Finally, the program prints the value of `y`, which is `6.4`.
We can also access a tuple element directly by using a period (`.`) followed by the index of the value we want to access. For example:
Filename: src/main.rs
```
fn main() {
let x: (i32, f64, u8) = (500, 6.4, 1);
let five_hundred = x.0;
let six_point_four = x.1;
let one = x.2;
}
```
This program creates the tuple `x` and then accesses each element of the tuple using their respective indices. As with most programming languages, the first index in a tuple is 0.
The tuple without any values has a special name, *unit*. This value and its corresponding type are both written `()` and represent an empty value or an empty return type. Expressions implicitly return the unit value if they donât return any other value.
#### [The Array Type](https://doc.rust-lang.org/book/ch03-02-data-types.html#the-array-type)
Another way to have a collection of multiple values is with an *array*. Unlike a tuple, every element of an array must have the same type. Unlike arrays in some other languages, arrays in Rust have a fixed length.
We write the values in an array as a comma-separated list inside square brackets:
Filename: src/main.rs
```
fn main() {
let a = [1, 2, 3, 4, 5];
}
```
Arrays are useful when you want your data allocated on the stack, the same as the other types we have seen so far, rather than the heap (we will discuss the stack and the heap more in [Chapter 4](https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#the-stack-and-the-heap)) or when you want to ensure that you always have a fixed number of elements. An array isnât as flexible as the vector type, though. A vector is a similar collection type provided by the standard library that *is* allowed to grow or shrink in size because its contents live on the heap. If youâre unsure whether to use an array or a vector, chances are you should use a vector. [Chapter 8](https://doc.rust-lang.org/book/ch08-01-vectors.html) discusses vectors in more detail.
However, arrays are more useful when you know the number of elements will not need to change. For example, if you were using the names of the month in a program, you would probably use an array rather than a vector because you know it will always contain 12 elements:
```
#![allow(unused)]
fn main() {
let months = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
}
```
You write an arrayâs type using square brackets with the type of each element, a semicolon, and then the number of elements in the array, like so:
```
#![allow(unused)]
fn main() {
let a: [i32; 5] = [1, 2, 3, 4, 5];
}
```
Here, `i32` is the type of each element. After the semicolon, the number `5` indicates the array contains five elements.
You can also initialize an array to contain the same value for each element by specifying the initial value, followed by a semicolon, and then the length of the array in square brackets, as shown here:
```
#![allow(unused)]
fn main() {
let a = [3; 5];
}
```
The array named `a` will contain `5` elements that will all be set to the value `3` initially. This is the same as writing `let a = [3, 3, 3, 3, 3];` but in a more concise way.
#### [Array Element Access](https://doc.rust-lang.org/book/ch03-02-data-types.html#array-element-access)
An array is a single chunk of memory of a known, fixed size that can be allocated on the stack. You can access elements of an array using indexing, like this:
Filename: src/main.rs
```
fn main() {
let a = [1, 2, 3, 4, 5];
let first = a[0];
let second = a[1];
}
```
In this example, the variable named `first` will get the value `1` because that is the value at index `[0]` in the array. The variable named `second` will get the value `2` from index `[1]` in the array.
#### [Invalid Array Element Access](https://doc.rust-lang.org/book/ch03-02-data-types.html#invalid-array-element-access)
Letâs see what happens if you try to access an element of an array that is past the end of the array. Say you run this code, similar to the guessing game in Chapter 2, to get an array index from the user:
Filename: src/main.rs
```
```
This code compiles successfully. If you run this code using `cargo run` and enter `0`, `1`, `2`, `3`, or `4`, the program will print out the corresponding value at that index in the array. If you instead enter a number past the end of the array, such as `10`, youâll see output like this:
```
thread 'main' panicked at src/main.rs:19:19:
index out of bounds: the len is 5 but the index is 10
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
```
The program resulted in a runtime error at the point of using an invalid value in the indexing operation. The program exited with an error message and didnât execute the final `println!` statement. When you attempt to access an element using indexing, Rust will check that the index youâve specified is less than the array length. If the index is greater than or equal to the length, Rust will panic. This check has to happen at runtime, especially in this case, because the compiler canât possibly know what value a user will enter when they run the code later.
This is an example of Rustâs memory safety principles in action. In many low-level languages, this kind of check is not done, and when you provide an incorrect index, invalid memory can be accessed. Rust protects you against this kind of error by immediately exiting instead of allowing the memory access and continuing. Chapter 9 discusses more of Rustâs error handling and how you can write readable, safe code that neither panics nor allows invalid memory access. |
| Shard | 127 (laksa) |
| Root Hash | 10528148938741058127 |
| Unparsed URL | org,rust-lang!doc,/book/ch03-02-data-types.html s443 |