14. Control Flow - IF ( Typescript vs Rust )
=> IF Control Flow in TypeScript
1. Condition: The if statement evaluates a condition that returns a boolean (true or false).
2. Block Scope: Variables declared within an if block are scoped to that block.
3. Type Guarding: TypeScript allows for type narrowing within if blocks.
==> Basic Example
function checkNumber(num: number) {
if (num > 0) {
console.log(`${num} is positive`);
} else if (num < 0) {
console.log(`${num} is negative`);
} else {
console.log(`${num} is zero`);
}
}
Typescript checks for truthy/falsy value meaning its not necessary to keep boolean value in condition.
=> IF Control Flow in Rust
1. Condition Type: The condition in a Rust if statement must be a boolean (bool).
2. No Implicit Conversion: Unlike TypeScript, Rust does not perform implicit conversion to boolean in if conditions.
3. if as an Expression: In Rust, "if" can be used as an expression to return values.
==> Basic Example
fn check_number(num: i32) {
if num > 0 {
println!("{} is positive", num);
} else if num < 0 {
println!("{} is negative", num);
} else {
println!("{} is zero", num);
}
}
==> if as an Expression in Rust
fn main() {
let num = -5;
let abs = if num < 0 { -num } else { num };
}
we can use if on the right side of a let statement to assign the outcome to a variable.
Values in each arm of if must of of same type meaning value returned from if and else must be of same type.
Below code will not compile because if is returning number and else is returning string.
fn main() {
let num = -5;
let value = if num < 0 { 0 } else { "hello" };
}
That's a wrap.