Menu
Coddy logo textTech

Type Declaration

Part of the Fundamentals section of Coddy's Rust journey — lesson 10 of 75.

Once a variable is declared with a certain type, it can only hold values of that type. For instance, an i32 variable can only hold integer values, and a String variable can only hold text.

For example:

let mut age: i32 = 25;  // Can only hold whole numbers
let mut name: &str = "Alice";  // Can only hold text

These would cause errors:

age = "Bob";  // Error: can't put text in an i32 variable
name = 30;  // Error: can't put a number in a String variable

These are valid:

age = 26;  // OK: assigning a new integer
name = "Jane";  // OK: assigning a new text string
challenge icon

Challenge

Beginner

Declare the following variables with their corresponding types and values:

  • An i32 variable named count with the value 10.
  • An f64 variable named total with the value 150.75.
  • A char variable named grade with the value 'A'.
  • A bool variable named is_active with the value false.
  • A String variable named user_name with the value "Bob123".

After declaring these variables, use println!() to output the values of the variables to the console in the following format:

Count: [value of count]
Total: [value of total]
Grade: [value of grade]
Active: [value of is_active]
User Name: [value of user_name]

Cheat sheet

Variables in Rust have fixed types and can only hold values of that specific type:

let mut age: i32 = 25;        // Integer variable
let mut name: &str = "Alice"; // String variable

Once declared, you can only assign values of the same type. Variables must be declared with mut to allow reassignment:

age = 26;        // Valid: assigning another integer
name = "Jane";   // Valid: assigning another string

age = "Bob";     // Error: can't assign text to i32
name = 30;       // Error: can't assign number to String

Common Rust types include:

  • i32 - 32-bit integers
  • f64 - 64-bit floating point numbers
  • char - single characters (use single quotes)
  • bool - boolean values (true/false)
  • String - text strings

Try it yourself

fn main() {
    // Declare variables here
    
    
    // Output the values
    println!("Count: {}", count);
    println!("Total: {}", total);
    println!("Grade: {}", grade);
    println!("Active: {}", is_active);
    println!("User Name: {}", user_name);
    
}
quiz iconTest yourself

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

All lessons in Fundamentals