Rust from zero: a name has a type
A Rust name has a type. name is a string slice, cents is an i32, and ready is a bool. The program prints latte $4.50 ready.
Piere is one of GoByte's characters. This post was drafted by AI agents in Piere's voice, then fact checked, run and edited by the GoByte team.
Rust wants a type for every name. A cup label needs three. &str is borrowed text, the type of a drink name written in the program. i32 is a whole number, the price in cents. bool is true or false, whether you can hand the drink over. You can write the type yourself, or let the compiler fill it in from the value. Either way, a mismatch is a compile error, not a surprise at runtime.
The type is on the binding#
let cents: i32 creates a binding whose type is a 32-bit signed integer. The type is part of the binding, and the compiler rejects a use that does not fit. i32 is not int. Rust wants the width. &str is a borrowed view of text that lives in the binary, which is the right type for a literal you only read. String, in the next lesson, is text the program owns. println! formats the label. It does not change the values. The dollars are cents / 100. The leftover cents are cents % 100.
- name&strlatte
- centsi32450
- readybooltrue
fn main() {
let name: &str = "latte";
let cents: i32 = 450;
let ready: bool = true;
let status = if ready { "ready" } else { "sold out" };
println!("{name} ${}.{:02} {status}", cents / 100, cents % 100);
}
latte $4.50 ready
The colon writes the type#
let cents: i32 = 450 makes cents, says it is an i32, and stores 450. That is $4.50, and the integer never holds the decimal point. println! is a macro. {name} prints the drink. {:02} prints the leftover cents as two digits, so 50 stays 50 and 5 would become 05. ready chooses the status word.
let cents = 450 is also an i32. The lesson writes the type so you can point at it. Later, when a function returns a value, the type on the function is the one that matters, and the let can leave it out.
The compiler refuses a mixed sum#
cents + name does not compile. An i32 and a &str have no +. The error names both types. To put the number on the label, use the format string, which is what println! already did. The next lesson puts a String and an i32 on a struct and calls a method that returns the same kind of label.
Your product here? Partner with us
Back to topDiscussion
No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines
Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.