Type Basics
Learn the fundamentals of Rust's type system
Basic Types
A type is the 'kind of data' something is. Numbers and text that we use every day are completely different things to a computer. The integer 5, the decimal 5.0, and the string '5' are all treated as different types. In Rust, clearly distinguishing what kind of data each piece is helps improve program safety. For example, if you try to calculate with text and numbers mixed up, Rust will catch it at compile time.
- Integer types (like i32): Numbers without decimal points like -5, 0, 42. i32 means a 32-bit integer
- Floating-point types (like f64): Numbers with decimals like 3.14, 2.5. f64 is a 64-bit floating-point number
- Boolean type (bool): Only two values - true or false. Used for conditional checks
- Character type (char): Single characters like 'a', 'æ°¸'. Enclosed in single quotes
- String types (&str, String): Sequences of characters like "hello". Enclosed in double quotes
Specifying Types
When creating a variable, you can explicitly specify what kind of data box it is. This is called type annotation. By writing the type name after a colon (:), you can declare 'this variable will only hold integers.' Specifying types makes code easier to understand for readers, and Rust will warn you if you try to put in data of the wrong type.
Type Inference - Rust Decides Automatically
Actually, Rust can intelligently figure out types without you writing them every time. This is called type inference. For example, when you write let x = 42;, Rust automatically understands '42 is an integer, so x must be an integer type.' Type inference makes code shorter and more readable, but you can still write types explicitly when needed for clarity or complex cases. Type inference is one of Rust's convenient features that keeps code simple while maintaining safety.
Usually it's fine to omit types. But when it's unclear to readers or for complex types, writing them explicitly is helpful.