Sub topic 8
Floats, booleans, and characters
This chapter covers the three remaining scalar types besides integers: floating-point numbers, bool, and char. It assumes you can declare variables with let, read compiler errors, and know how integer types and annotations work from earlier chapters.
Floating-point types
Rust has two floating-point types: f32 (32 bits) and f64 (64 bits). Both follow the IEEE 754 standard. When inference has no other information, a literal such as 2.5 becomes f64. That default is usually right on modern CPUs, because f64 is about as fast as f32 and has more precision.
fn main() {
let a = 2.5; // f64 by default
let b: f32 = 2.5; // explicit f32
let c = 1e3; // 1000.0, scientific notation
let d = 3.0_f32; // suffix sets the type
println!("{a} {b} {c} {d}");
}A literal needs a decimal point or exponent to be a float. 3 is an integer, and 3.0 is a float.
Arithmetic and mixing types
Rust never converts between numeric types implicitly. You cannot add an i32 to an f64, and you cannot add an f32 to an f64.
fn main() {
let count: i32 = 4;
let price: f64 = 2.5;
// let total = count * price; // error[E0277]: cannot multiply `i32` by `f64`
let total = f64::from(count) * price;
println!("{total}");
}Integer division truncates, while float division does not: 7 / 2 is 3, but 7.0 / 2.0 is 3.5.
NaN and equality
Floats include special values: f64::INFINITY, f64::NEG_INFINITY, and NaN (not a number). Dividing a float by zero does not panic. It produces infinity or NaN. NaN is not equal to anything, including itself.
fn main() {
let nan = 0.0_f64 / 0.0;
println!("{}", nan == nan); // false
println!("{}", nan.is_nan()); // true
println!("{}", 0.1 + 0.2 == 0.3); // false
println!("{}", (0.1_f64 + 0.2 - 0.3).abs() < 1e-9); // true
}Because NaN != NaN, floats implement PartialEq and PartialOrd but not Eq or Ord. As a result, you cannot use floats as HashMap keys or call .sort() on a Vec<f64>. Use sort_by with total_cmp instead.
Binary fractions cannot represent 0.1 exactly, so compare with a tolerance, as the last line above does.
Booleans
bool has two values, true and false, and takes one byte. Operators && and || short-circuit: the right side runs only if needed. ! negates.
fn main() {
let ready = true;
let verbose: bool = false;
let n = 7;
let is_small_and_odd = n < 10 && n % 2 == 1;
println!("{} {} {}", !ready, verbose || ready, is_small_and_odd);
}Conditions in if and while must be bool. Rust has no "truthy" values, so if n { ... } with an integer n is a compile error. Write if n != 0 instead.
Characters
char represents one Unicode scalar value. It is written with single quotes and takes four bytes. This differs from C, where char is one byte.
fn main() {
let letter = 'a';
let heart = '❤';
let tab = '\t';
let from_code = '\u{1F600}';
println!("{letter} {heart} {from_code} {}", tab.is_whitespace());
println!("{}", 'a'.len_utf8());
println!("{}", '❤'.len_utf8());
}Single quotes make a char. Double quotes make a &str, which is a string slice. 'a' and "a" are different types.
A char is a Unicode scalar value, not a "character" as a person sees it. An accented letter written as a base letter plus a combining mark is two char values. That distinction matters when you handle text, which a later chapter covers.
Useful char methods include is_alphabetic, is_ascii_digit, to_ascii_uppercase, and to_digit(10), which returns an Option<u32>.
Common errors
| Mistake | Result | Fix |
|---|---|---|
| `let x: f64 = 5;` | Type mismatch, integer literal | Write `5.0` |
| `1.5_f32 + 1.5_f64` | Mismatched types | Convert with `f64::from` |
| `if count { }` | Expected `bool` | Compare: `count != 0` |
| `let c = "a"; let d: char = c;` | `&str` is not `char` | Use `'a'` |
Exercise
Why does let v = vec![2.5, 1.0]; v.sort(); fail to compile, and what is the fix for a Vec<f64>?
Show answer
f64 does not implement Ord because NaN has no consistent ordering, and sort requires Ord. Declare let mut v and call v.sort_by(|a, b| a.total_cmp(b)), which defines a total order that includes NaN.
Exercise
What is the value of 'a'.len_utf8() compared with std::mem::size_of::<char>(), and why do they differ?
Show answer
'a'.len_utf8() is 1, because UTF-8 encodes ASCII in one byte. size_of::<char>() is 4, because a char in memory always holds a full Unicode scalar value in 32 bits.