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 textThese 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 variableThese are valid:
age = 26; // OK: assigning a new integer
name = "Jane"; // OK: assigning a new text stringChallenge
BeginnerDeclare the following variables with their corresponding types and values:
- An
i32variable namedcountwith the value10. - An
f64variable namedtotalwith the value150.75. - A
charvariable namedgradewith the value'A'. - A
boolvariable namedis_activewith the valuefalse. - A
Stringvariable nameduser_namewith 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 variableOnce 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 StringCommon Rust types include:
i32- 32-bit integersf64- 64-bit floating point numberschar- 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);
}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