Variable Binding
Part of the Fundamentals section of Coddy's Rust journey — lesson 47 of 75.
In Rust, when we say let var;, we're creating a "binding." Think of it as reserving a name (var) that will be connected (or "bound") to a value later.
Direct Binding (Most Common):
// Declare AND initialize in one step
let x = 2;This is what you'll use 90% of the time. It's clean and straightforward.
Separate Declaration and Initialization:
let var; // Just declaring
let x = 2;
var = x * x; // Initializing laterWhy Have Separate Declaration?
Conditional Initialization:
let number;
if some_condition {
number = 1;
} else {
number = 2;
}Complex Calculations:
let result;
// ... some complex logic ...
result = final_value;When Working with Scopes:
let outside;
{
let inside = 42;
outside = inside * 2;
}
// inside is gone, but outside keeps its valueCheat sheet
In Rust, let var; creates a "binding" - reserving a name that will be connected to a value.
Direct Binding (Most Common):
let x = 2;Separate Declaration and Initialization:
let var; // Just declaring
let x = 2;
var = x * x; // Initializing laterUse cases for separate declaration:
Conditional initialization:
let number;
if some_condition {
number = 1;
} else {
number = 2;
}Working with scopes:
let outside;
{
let inside = 42;
outside = inside * 2;
}
// inside is gone, but outside keeps its valueTry it yourself
This lesson doesn't include a code challenge.
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