Numbers, booleans and characters
Every value in Rust has a type. Here are the simple ones.
Integers
Whole numbers are integers. i types can be negative; u types can't. The number after the letter is the size in bits.
| Type | Holds |
|---|---|
i32 | -2 billion to 2 billion (the default) |
u8 | 0 to 255 |
i64, u32 | bigger or unsigned ranges |
let x = 42; makes an i32. You can write 1_000_000 to make big numbers easy to read.
Floats
Numbers with a decimal point are floats. The default is f64; f32 is smaller.
let price = 9.99; // f64let x: f64 = 1.0; // write 1.0, not 1Integer division
Dividing two integers drops the remainder. % gives the remainder.
println!("{}", 7 / 2); // 3println!("{}", 7 % 2); // 1println!("{}", 7.0 / 2.0); // 3.5bool and char
A bool is true or false. Comparisons give a bool: == (equal), != (not equal), <, >, <= and >=. So 10 > 3 is true. Join bools with && (and) and || (or), and flip one with ! (not).
A char is one character in single quotes, like 'a' or '馃'. Double quotes, like "a", make text, not a char.
Casting with as
Rust never mixes number types for you. Adding an i32 to an f64, or putting an i32 where an i64 is wanted, is an error. Use as to convert:
let a: i32 = 5;let b: f64 = 2.5;let c = a as f64 + b; // 7.5let n = 9.99 as i32; // 9, the decimals are cut offA char can become its number too: 'A' as u32 is 65.
Remember
- Integers are
i32and floats aref64unless you say otherwise. 7 / 2is3, and7 % 2is1.charuses single quotes.- Convert numbers with
as.