Sub topic 8
Floats, booleans, and characters
This chapter covers the three non-integer scalar types: floating-point numbers (f32, f64), the boolean bool, and the Unicode character char. It assumes you know let bindings, type inference and annotations, and the integer types from the earlier chapters. It also assumes you can run a program with cargo run. The as operator is previewed here, and the chapter on conversions covers it fully.
Floating-point types
Rust has two floating-point types. f32 is a 32-bit IEEE 754 single-precision number. f64 is a 64-bit double-precision number. When a literal like 2.0 has no other constraint, inference picks f64. On modern CPUs f64 is usually about as fast as f32, so use f32 only when memory or a required format (graphics, audio, GPU buffers) calls for it.
A float literal needs a digit on both sides of the point or an exponent. 2. is valid, but .5 is not. You can add underscores for readability and a type suffix to fix the type.
fn main() {
let a = 2.0;
let b: f32 = 2.5;
let c = 1e3;
let d = 7_f32 / 2.0;
println!("{a:?} {b:?} {c:?} {d:?}");
println!("{}", 0.1 + 0.2);
println!("{}", 0.1 + 0.2 == 0.3);
let diff = ((0.1_f64 + 0.2) - 0.3).abs();
println!("{}", diff < f64::EPSILON);
println!("{}", 16_777_217_f32);
}This prints 2.0 2.5 1000.0 3.5, then 0.30000000000000004, false, true, and 16777216. The last line shows that f32 has a 24-bit significand, so it cannot represent 16,777,217 and rounds to the nearest even neighbor.
Why `0.1 + 0.2 != 0.3`
Binary floating point cannot represent most decimal fractions exactly. Each literal is stored as the nearest representable value, and the small errors show up after arithmetic. Compare floats with a tolerance, not with ==. f64::EPSILON is the gap between 1.0 and the next representable number. It suits values near 1, but for larger or smaller magnitudes you should scale the tolerance.
Do not use floats for money. Store integer cents, or use a decimal crate.
Special values and ordering
Floating-point arithmetic never panics. Dividing a float by zero produces infinity, and an undefined operation produces NaN (not a number). Integer division by zero, by contrast, panics.
fn main() {
let inf = 1.0_f64 / 0.0;
let nan = 0.0_f64 / 0.0;
println!("{inf} {}", -inf);
println!("{}", nan == nan);
println!("{}", nan.is_nan());
let mut v: Vec<f64> = vec![3.2, 1.5, 2.7];
v.sort_by(|a, b| a.total_cmp(b));
println!("{v:?}");
}The output is inf -inf, false, true, and [1.5, 2.7, 3.2].
NaN is not equal to anything, including itself. Because of this, floats implement PartialEq and PartialOrd but not Eq or Ord. The consequences are practical:
- You cannot use
f64as aHashMapkey or in aBTreeSetdirectly. v.sort()does not compile for aVec<f64>. Usesort_bywithf64::total_cmp, which defines a total order that placesNaNafter infinity.partial_cmpreturnsOption<Ordering>, and it isNonewhenNaNis involved.
Floats and `as`
Casting a float to an integer with as truncates toward zero and saturates at the target's bounds. NaN becomes 0. This differs from integer-to-integer as, which wraps.
fn main() {
println!("{}", 3.99_f64 as i32);
println!("{}", 300.7_f64 as u8);
println!("{}", -5.0_f64 as u8);
println!("{}", f64::NAN as i32);
}This prints 3, 255, 0, and 0. The casts never fail, so a bad value turns into a plausible-looking one. Check for NaN and range before casting when the input is untrusted.
Booleans
bool has two values, true and false. It occupies one byte. Rust never converts other types to bool implicitly, so if n { ... } with an integer n is a type error (E0308). Write the comparison you mean, such as n != 0.
The logical operators are:
| Operator | Meaning | Evaluates right side | Column | Column |
|---|---|---|---|---|
| `&&` | logical AND | only if the left side is `true` | ||
| `\ | \ | ` | logical OR | only if the left side is `false` |
| `&` | AND without short-circuit | always | ||
| `\ | ` | OR without short-circuit | always | |
| `^` | exclusive OR | always | ||
| `!` | NOT | not applicable |
Short-circuiting matters when the right side has side effects or is expensive. It is also what makes guards like i < v.len() && v[i] > 0 safe.
fn expensive() -> bool {
println!("expensive called");
true
}
fn main() {
let ready = false;
let a = ready && expensive();
let b = ready & expensive();
println!("{a} {b}");
let n = 3;
let is_positive = n > 0;
println!("{}", is_positive as i32 + i32::from(true));
println!("{:?}", (n > 2).then_some("big"));
}The output is:
expensive called
false true
2
Some("big")expensive called appears once, from the & line. A bool converts to an integer with as or From, where true becomes 1 and false becomes 0. The reverse direction does not exist, so write x != 0. The methods then_some(value) and then(|| value) turn a bool into an Option. Use then when computing the value is costly.
Characters
A char is a single Unicode scalar value, written with single quotes: 'a'. It is 4 bytes wide. A scalar value is any code point from U+0000 to U+10FFFF except the surrogate range U+D800 to U+DFFF. Double quotes make a &str, not a char, so 'a' and "a" are different types.
fn main() {
let letter = 'a';
let heart = '❤';
let crab = '\u{1F980}';
println!("{letter} {heart} {crab}");
println!("{} {}", 'é'.len_utf8(), crab.len_utf8());
println!("{}", std::mem::size_of::<char>());
println!("{}", letter as u32);
println!("{}", 97u8 as char);
println!("{:?}", char::from_u32(0xD800));
println!("{:?}", char::from_u32(0x41));
println!("{:?} {:?}", '7'.to_digit(10), 'x'.to_digit(10));
println!("{}", 'ß'.to_uppercase());
}The output is:
a ❤ 🦀
2 4
4
97
a
None
Some('A')
Some(7) None
SSConversions to and from `char`
char as u32always works, and it gives the code point.u8 as charis the only integer cast tocharthatasallows. Everyu8is a valid scalar, so it cannot fail.char::from(65u8)does the same thing.char::from_u32(n)returnsOption<char>, because values such as 0xD800 are not valid.c.to_digit(radix)andchar::from_digit(d, radix)convert between digit characters and numbers.
Because char is a scalar value, to_uppercase() returns an iterator. A single character can expand to several: 'ß' becomes "SS". If you only need ASCII, to_ascii_uppercase() returns one char.
A `char` is not a "letter on screen"
A char is not a byte, and it is not what a reader perceives as one character. A string like "é" can be one scalar (U+00E9) or two (e followed by the combining accent U+0301). The second form gives "e\u{301}".chars().count() == 2 even though it displays as one glyph. Counting user-perceived characters (grapheme clusters) needs the unicode-segmentation crate. Strings are stored as UTF-8, so a string's byte length (len()) and its char count (chars().count()) are different numbers. A later chapter on strings covers this.
Choosing among the scalar types
The sizes and defaults for these types are:
| Type | Size | Default when inferred | Ordering traits |
|---|---|---|---|
| `f32` | 4 bytes | no | `PartialOrd` only |
| `f64` | 8 bytes | yes, for float literals | `PartialOrd` only |
| `bool` | 1 byte | not applicable | `Ord` |
| `char` | 4 bytes | not applicable | `Ord`, by code point |
bool and char implement Eq, Ord, and Hash, so they work as map keys and can be sorted. Comparing char values compares code points, which is not the same as alphabetical order in most languages.
Common errors
- Mixing
f32andf64.1.5_f32 + 2.0_f64fails with E0277 (cannot addf64tof32). Convert one side explicitly withasorf64::from(x). - Mixing integers and floats.
let x = 3 * 1.5;fails because there is no implicit promotion. Write3.0 * 1.5orf64::from(3) * 1.5. - Comparing floats with
==. This compiles but gives surprising results. Use a tolerance. - Using double quotes for a
char.let c: char = "a";is a type mismatch. Use'a'. - Multi-character literals.
'ab'is a compile error. Use a&str. - Sorting or hashing floats. Use
total_cmp, or wrap the value in a type that defines ordering.
Exercise
A function must return the largest value in a Vec<f64>. Why does v.iter().max() not compile, and what could you write instead so that it compiles and treats NaN in a defined way?
Show answer
max requires the element type to implement Ord, and f64 implements only PartialOrd because NaN is not comparable. Use v.iter().copied().max_by(|a, b| a.total_cmp(b)), which returns an Option<f64>. total_cmp defines a total order in which positive NaN is larger than every other value, so a positive NaN in the input would be returned as the maximum. To ignore NaN instead, filter it out first with .filter(|x| !x.is_nan()).
Exercise
What do 'a' as u32, char::from_u32(0xD800), and 300.7_f64 as u8 evaluate to, and which one can fail without any warning at run time?
Show answer
'a' as u32 is 97. char::from_u32(0xD800) is None, because that code point is a surrogate and not a valid scalar value. 300.7_f64 as u8 is 255, since a float-to-integer as cast saturates. The float cast is the one that silently produces a wrong-looking value. The char::from_u32 call reports its failure through Option, and the first cast cannot fail.