A quantity, a price and a yes-or-no flag need different types. Rust checks types at compile time and can usually infer them from values and their use.[1] An annotation makes your choice explicit: put a colon and the type after the variable name.[1]
Give each value a type
These examples were tested on Linux ARM64 with rustc 1.99.1 and Cargo 1.99.1. Create a fresh project, then open its types folder in your editor and terminal.
cargo new --vcs none types
$ cargo new --vcs none types Creating binary (application) `types` packagenote: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.htmlexit=0
Replace src/main.rs with this complete programme. Use i32 for a signed, 32-bit whole number; f64 is a 64-bit floating-point type; bool holds true or false.[1] The names describe what these values represent.
fn main() { let items: i32 = 3; let price: f64 = 2.5; let ready: bool = true; println!("Items: {items}"); println!("Price: {price}"); println!("Ready: {ready}");}
Integers have finite ranges, and floating-point types have limited precision.[1] Choose a type that suits the data you expect to store. We use small values here so the first checkpoint stays focused on the declarations.
Run the programme from the types folder. The terminal captures below include the executed command and its exit status.
cargo run --quiet
$ cargo run --quietItems: 3Price: 2.5Ready: trueexit=0
Our programme printed each value on its own line. Removing all three annotations produced the same output in our second run. For these unconstrained numeric literals, the integer default is i32 and the floating-point default is f64.[1]

A common error: a number in a Boolean
Replace src/main.rs with this deliberately failing version.
fn main() { let ready: bool = 1; println!("Ready: {ready}");}
Check it without producing an executable.[3]
cargo check --quiet
$ cargo check --quieterror[E0308]: mismatched types --> src/main.rs:2:23 |2 | let ready: bool = 1; | ---- ^ expected `bool`, found integer | | | expected due to thisFor more information about this error, try `rustc --explain E0308`.error: could not compile `types` (bin "types") due to 1 previous errorexit=101
Our check stopped at the value 1. Read expected as the required type and found as the supplied type: the annotation requires bool, while the value is an integer. E0308 reports a type mismatch.[2]
Use true or false for the flag.[1] Keep the annotation while learning: it gives you a clear place to compare your intended type with the compiler’s diagnostic.
Exercise
Restore the working programme and change ready to false. Run it again. Expect the final line to become Ready: false while the first two lines stay unchanged.
Next: functions with parameters, return values and expressions.
Browse Rust, one step at a time
Leave a Reply