Menu
CoddyTech

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 icon

Challenge

Beginner

Write a Rust program that declares and initializes the following variables:

  • Declare an i32 variable named quantity and initialize it with the value 5.
  • Declare an f64 variable named item_price and initialize it with the value 24.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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online Rust compiler