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 can specify the type of the variable after its name and a colon. This is known as type declaration. The type is optional when Rust can infer it from the value: let count = 100; is an i32 and let price = 99.99; is an f64. 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.
The lines below your code print them in this format:
Quantity: [value of quantity]
Price: [value of item_price]Try it yourself
// Declare and initialize variables here
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 InputPractice on your own: Online Rust compiler