Sub topic 3
Floats, Booleans, and Characters
Assume you know basic variables, functions, loops, and how to read simple compiler errors. Rust checks types at compile time, but it often infers a type from context.
Floats, booleans, and characters
Rust provides f32 and f64 floating-point types. Use f64 by default when precision matters. A bool is either true or false. A char stores one Unicode scalar value and uses single quotes.
fn main() {
let temperature: f64 = 21.5;
let ready: bool = temperature > 20.0;
let symbol: char = '✓';
println!("{temperature} {ready} {symbol}");
}Floating-point calculations can produce rounding errors. Do not use direct equality for values that should be mathematically equal after calculation.
Integer overflow in debug and release builds
For ordinary integer arithmetic, a debug build usually panics on overflow. An optimized release build usually wraps the result. Do not depend on either default. Choose the behavior explicitly:
| Method | Result when overflow occurs |
|---|---|
| `checked_add` | `Option`, with `None` on overflow |
| `wrapping_add` | Wraps around |
| `saturating_add` | Stops at the type's maximum |
| `overflowing_add` | Returns the wrapped value and a flag |
fn main() {
let value: u8 = 250;
println!("{:?}", value.checked_add(10)); // None
println!("{}", value.wrapping_add(10)); // 4
println!("{}", value.saturating_add(10)); // 255
}Compound types: tuples and arrays
A tuple groups a fixed number of values that may have different types. An array has a fixed length and one element type.
fn main() {
let point: (i32, f64, char) = (3, 2.5, 'x');
let (x, y, label) = point;
let bytes = [0u8; 4];
println!("{x} {y} {label} {}", bytes.len());
}Converting between types safely
Use as for conversions whose behavior you understand. It can truncate or wrap numeric values. Prefer From for infallible conversions, TryFrom for conversions that can fail, and parse for text.
A first look at interior mutability
Interior mutability lets a type change its value through an immutable binding or shared reference. Cell<T> provides this for copyable values.
use std::cell::Cell;
fn main() {
let count = Cell::new(1);
count.set(count.get() + 1);
println!("{}", count.get());
}Exercise
Which method should you choose when an overflowing calculation must report failure?
Show answer
Use a checked method such as checked_add; it returns None on overflow.