Numbers
Part of the Fundamentals section of Coddy's Rust journey — lesson 5 of 75.
Variables are containers that hold data values. They are used to store, manipulate, and display information within a program.
In short a variable is like a memory unit that we can access by typing the name of the variable.
Each variable has a unique name and a value that can be of different types. Rust has various built-in data types that define the type of value a variable can hold.
To initialize a variable, we use the following format:
let variable_name: variable_type = value;In Rust, numbers are typically represented using two main data types: i32 and f64.
i32 is used to store whole numbers without any decimal point. For example:
let age: i32 = 30;
let temperature: i32 = -5;
let count: i32 = 100;f64 is used to store numbers with a decimal point. For example:
let price: f64 = 99.99;
let pi: f64 = 3.14159;
let fraction: f64 = 0.5;When declaring variables in Rust, you need to specify the type of the variable after the variable name, followed by a colon. This is known as type declaration. Once a variable is declared with a certain type, it can only hold values of that type.
Challenge
BeginnerWrite a Rust program that declares and initializes the following variables:
- Declare an
i32variable namedquantityand initialize it with the value5. - Declare an
f64variable nameditem_priceand initialize it with the value24.99.
After declaring and initializing these variables, use println!() to output the values of the variables to the console in the following format:
Quantity: [value of quantity]
Price: [value of item_price]Cheat sheet
Variables are containers that hold data values. To initialize a variable, use this format:
let variable_name: variable_type = value;i32 is used for whole numbers:
let age: i32 = 30;
let temperature: i32 = -5;f64 is used for numbers with decimal points:
let price: f64 = 99.99;
let pi: f64 = 3.14159;Type declaration is required - specify the type after the variable name with a colon. Once declared, a variable can only hold values of that type.
Try it yourself
fn main() {
// Declare and initialize variables here
// Output the values, Don't change the lines below
println!("Quantity: {}", quantity);
println!("Price: {}", item_price);
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 33Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic Input