Integers
- Rust course
- Beginner
- Lesson 13/115
- 4 min
Learn signed and unsigned integer types like i32 and u64.
Integers
Rust splits integers into signed (i8, i16, i32, i64, i128) and unsigned (u8 … u128); the number is the bit width. isize/usize match the CPU width and are used for indexes. The default is i32.
let a: u8 = 255; // 0..=255
let b: i8 = -128; // -128..=127
let buyuk = 1_000_000; // _ is for readability
let hex = 0xff; // 255u8 is ideal for a byte; IDs and counters usually use u32/u64.
Overflow and explicit behavior
Overflow at run time panics in debug builds. Methods are used to choose the behavior explicitly:
let x: u8 = 250;
println!("{:?}", x.checked_add(10)); // None
println!("{}", x.wrapping_add(10)); // 4
println!("{}", x.saturating_add(10)); // 255In money and counter calculations, the checked_* methods let you catch overflow as an error.
Practice Overflow methods
For let x: u8 = 250;, print x.checked_add(10), x.wrapping_add(10) and x.saturating_add(10) with println!("{:?} {} {}", ...).
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let x: u8 = 250;
println!("{:?} {} {}", x.checked_add(10), x.wrapping_add(10), x.saturating_add(10));
}Expected output
None 4 255
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens with <code>let x: u8 = 256;</code>?
- A run-time panic
- Compile error: value out of range Correct answer
- x becomes 0
- x becomes 255
Explanation: u8 holds at most 255; the compiler rejects an overflowing literal at compile time.
2 Saturating add
let x: u8 = 250;
let y = x.____(10); // 255
let x: u8 = 250;
let y = x.saturating_add(10); // 255
Explanation: saturating_add stops at the type's maximum value on overflow.
3 Type and range
| Term | Meaning |
|---|---|
u8 |
0..=255 |
i8 |
-128..=127 |
usize |
Index type |
i32 |
Default integer |