Part 01 · Rust Is Not Scary

if, loop, while and for

ifloopwhileforRanges

Decision নেওয়া আর কাজ বারবার করা, আর Rust এ if কেন একটা value ফেরত দিতে পারে।

⏱ 9 মিনিট · Station 8 / 75

The story

একজন দোকানদারের দিন দুই রকম চিন্তা দিয়ে চলে। Decision: "bill হাজার টাকার বেশি হলে delivery free, না হলে ষাট টাকা"। আর বারবার করা: "basket এর প্রতিটা item দেখে দাম যোগ করো", "stock থাকা পর্যন্ত বিক্রি করতে থাকো", "আজকের target পূরণ না হওয়া পর্যন্ত চালিয়ে যাও"।

Code এরও এই দুইটা জিনিস লাগে। if decision নেয়। for, while আর loop কাজ বারবার করে। Rust এর version গুলো চেনা চেনা লাগবে, কিন্তু দুইটা twist আছে যেগুলো এদের safe বানায়: decision হতে হবে আসল true বা false, আর একটা if function এর মতো value ফেরত দিতে পারে।

The idea

if / else if / else একটা পথ choose করে। Condition হতে হবে bool। আর যেহেতু if একটা expression (function এর শেষ line এর মতো একই idea), এটা এমন value দিতে পারে যেটা সরাসরি variable এ রাখা যায়:

let delivery = if total >= 100_000 { 0 } else { 6_000 };

তিনটা loop, প্রত্যেকটা আলাদা রকম repetition এর জন্য:

Loopকখন use করবেShop এর example
for x in listএকটা list বা range এর ভেতর দিয়ে যেতে হবেbasket এর প্রতিটা দাম যোগ করা
while conditionকিছু একটা true থাকা পর্যন্ত চলবেstock > 0 থাকা পর্যন্ত বিক্রি
loopতুমি break দিয়ে থামানো পর্যন্ত চলবেtarget না হওয়া পর্যন্ত জমানো

Range লেখা হয় 1..=3 (1, 2, 3: শেষেরটা সহ) অথবা 1..3 (1, 2: শেষের আগে থামে)।

for price in prices { total += price; }420price = 420, total = 420185price = 185, total = 605150price = 150, total = 75560price = 60, total = 815priceno more items: the loop ends, total = 815
for price in prices প্রতিটা item এ ঠিক একবার যায়, order অনুযায়ী। প্রতিবার price হয় পরের item টা, আর running total বাড়তে থাকে: 420, 605, 755, 815। List শেষ হলে loop নিজে থেকেই থেমে যায়।

Try it: decisions and loops in the shop

Value হিসেবে if, আর দুইয়ের বেশি choice এর জন্য else if:

fn main() {
    let total = 75_500; // ৳755.00 in paisa

    // if is an expression: it gives back a value
    let delivery = if total >= 100_000 { 0 } else { 6_000 };
    println!("delivery: {delivery}");

    let tier = if total >= 200_000 {
        "gold"
    } else if total >= 50_000 {
        "silver"
    } else {
        "regular"
    };
    println!("customer tier: {tier}");
}
delivery: 6000
customer tier: silver

if এর প্রতিটা branch একই type এর value দেয় (এখানে একটা number, অথবা একটা text), আর যেটা choose হয় সেটা গিয়ে বসে delivery বা tier এ। তিন জায়গায় set করা কোনো mut variable নেই, একটা branch ভুলে যাওয়ার কোনো chance ও নেই।

তিনটা loop, একটা program এ:

fn main() {
    // for: go through every item in a list
    let prices = [420, 185, 150, 60];
    let mut total = 0;
    for price in prices {
        total += price;
        println!("added {price:>3}, total {total}");
    }

    // for over a range: 1..=3 means 1, 2, 3
    for day in 1..=3 {
        println!("day {day}");
    }

    // while: repeat as long as a condition is true
    let mut stock = 3;
    while stock > 0 {
        println!("sold one, {stock} were left");
        stock -= 1;
    }

    // loop: repeat until you break, and break can carry a value
    let mut saved = 0;
    let mut days = 0;
    let days_needed = loop {
        saved += 150;
        days += 1;
        if saved >= 1_000 {
            break days;
        }
    };
    println!("saving 150 a day, 1000 takes {days_needed} days");
}
আগে অনুমান করো

দিনে 150 টাকা করে জমালে, জমা 1000 হতে কয় দিন লাগবে?

added 420, total 420
added 185, total 605
added 150, total 755
added  60, total 815
day 1
day 2
day 3
sold one, 3 were left
sold one, 2 were left
sold one, 1 were left
saving 150 a day, 1000 takes 7 days

তিনটা জিনিস খেয়াল করো:

  • for price in prices একে একে প্রতিটা item দেয়। Manage করার মতো কোনো index নেই, তাই "একটা কম বা বেশি" ভুল নেই, list এর শেষ পার হয়ে read ও নেই।
  • while প্রতিটা round এর আগে condition check করে। stock 0 হলে condition false, loop আর চলে না।
  • break days দুইটা কাজ করে: loop থামায়, আর days কে loop এর value হিসেবে বের করে দেয়। তাই let days_needed = loop { ... }; ঠিক let x = if ... এর মতোই কাজ করে।

What the compiler says

Python আর JavaScript এ if stock: একটা number দিয়েও চলে: 0 মানে false, বাকি সব true। Rust রাজি না:

fn main() {
    let stock: u32 = 0;
    if stock {
        println!("in stock");
    }
}
error[E0308]: mismatched types
 --> src/main.rs:3:8
  |
3 |     if stock {
  |        ^^^^^ expected `bool`, found `u32`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `truthy` (bin "truthy") due to 1 previous error

expected `bool`, found `u32` : condition কে bool হতেই হবে। যা বোঝাতে চাও সেটাই লেখো: if stock > 0। মাত্র দুইটা character বেশি, আর যে পড়বে তাকে মনে রাখতে হবে না কোন কোন value "false" ধরা হয়।

if কে value হিসেবে use করার দুইটা rule আছে, আর compiler দুইটাই বুঝিয়ে দেয়। প্রথমত, সম্ভাব্য প্রতিটা পথকেই একটা value দিতে হবে, তাই else লাগবে:

fn main() {
    let total = 75_500;
    let delivery = if total >= 100_000 { 0 };
    println!("{delivery}");
}
error[E0317]: `if` may be missing an `else` clause
 --> src/main.rs:3:20
  |
3 |     let delivery = if total >= 100_000 { 0 };
  |                    ^^^^^^^^^^^^^^^^^^^^^^-^^
  |                    |                     |
  |                    |                     found here
  |                    expected integer, found `()`
  |
  = note: `if` expressions without `else` evaluate to `()`
  = help: consider adding an `else` block that evaluates to the expected type

For more information about this error, try `rustc --explain E0317`.
error: could not compile `noelse` (bin "noelse") due to 1 previous error
  • error[E0317]: `if` may be missing an `else` clause: total 100,000 এর নিচে হলে delivery কত? কোনো answer নেই।
  • note: `if` expressions without `else` evaluate to `()` : না-থাকা branch টা ফেরত দেয় (), মানে কিছুই না। আর যে variable এর number হওয়ার কথা, তাতে "কিছুই না" রাখা যায় না।
  • help: consider adding an `else` block: তাই একটা add করো।

দ্বিতীয়ত, প্রতিটা branch কে একই type দিতে হবে:

fn main() {
    let total = 75_500;
    let delivery = if total >= 100_000 { "free" } else { 6_000 };
    println!("{delivery}");
}
error[E0308]: `if` and `else` have incompatible types
 --> src/main.rs:3:58
  |
3 |     let delivery = if total >= 100_000 { "free" } else { 6_000 };
  |                                          ------          ^^^^^ expected `&str`, found integer
  |                                          |
  |                                          expected because of this

For more information about this error, try `rustc --explain E0308`.
error: could not compile `mixed` (bin "mixed") due to 1 previous error

expected `&str`, found integer: প্রথম branch দিয়েছে text, তাই compiler ধরে নিয়েছে delivery একটা text। তারপর else দিয়েছে number। একটা variable এর type একটাই, তাই একটা বেছে নাও: 0 আর 6_000, অথবা "free" আর "60 taka"।

Under the hood

for চলে একটা iterator দিয়ে। for price in prices, prices এর কাছে একটা iterator চায়। Iterator প্রতিবার পরের item টা দেয়, আর শেষে বলে "শেষ"। এজন্যই কোনো index নেই, আর শেষ পার হওয়ার কোনো উপায়ও নেই। Iterators এ iterator নিজে use করতে শিখবে। আপাতত এটুকু জানো: release mode এ একটা list এর উপর for loop compile হয়ে C তে হাতে লেখা index loop এর মতোই tight machine code হয়।

Range ও একটা value। 1..=3 হলো RangeInclusive type এর আসল একটা value, আর for এর উপর দিয়ে ঠিক list এর মতোই যায়।

Value হলে প্রতিটা if কে complete হতে হবে। এই rule, সাথে "প্রতিটা branch, একই type", এর ফলে compiler প্রমাণ করতে পারে যে delivery এর মতো variable সবসময় একটা value পায়। এমন কোনো পথ নেই যেখানে ওটা খালি থেকে যায়।

Loop এর নাম দেওয়া যায়। Loop এর ভেতরে loop থাকলে break থামায় সবচেয়ে ভেতরেরটা। বাইরের loop কে একটা label দাও, 'outer: for ..., তাহলে break 'outer; ওটাকে থামাবে। খুব বেশি লাগবে না, কিন্তু যখন লাগবে, একটা বাড়তি "found" flag বাঁচিয়ে দেবে।

Compared with other languages

bool condition নিয়ে Rust এত কড়া কেন? এখানে একটা আসল ধরনের bug। Form এর field আসে text হিসেবে, তাই শূন্য stock আসে "0" string হিসেবে:

const stockFromForm = "0"; // form fields always arrive as text
if (stockFromForm) {
  console.log("JS: in stock, show the Buy button");
}
const empty = [];
if (empty) {
  console.log("JS: an empty list is truthy too");
}
stock_from_form = "0"  # form fields always arrive as text
if stock_from_form:
    print("Python: in stock, show the Buy button")
JS: in stock, show the Buy button
JS: an empty list is truthy too
Python: in stock, show the Buy button

দুইটা language ই ধরে নিয়েছে "0" stock মানে "stock আছে", কারণ খালি না এমন string truthy। JavaScript তো খালি list কেও true ধরে। Shop এমন জিনিসের জন্য Buy button দেখাচ্ছে যেটা ওর কাছে নেই। Rust এ এই code compile ই হয় না: আগে "0" কে number এ parse করতে হতো, তারপর stock > 0 লিখতে হতো, আর bug টা কখনো হতোই না।

PythonJavaScriptGoRust
Conditionযেকোনো কিছু (truthy)যেকোনো কিছু (truthy)শুধু boolশুধু bool
if value দেয়a if c else bc ? a : bনাহ্যাঁ, if c { a } else { b }
Loopfor, whilefor, for..of, whileশুধু forfor, while, loop
Loop value দেয়নানানাloop এ break value

Key takeaway

if এর condition হতে হবে আসল একটা bool, তাই stock না লিখে লেখো stock > 0। if একটা expression: value ফেরত দিতে পারে, যদি else থাকে আর প্রতিটা branch একই type দেয়। List আর range এর ভেতর দিয়ে যেতে for (1..=3 এ 3 থাকে, 1..3 এ থাকে না), কিছু true থাকা পর্যন্ত চালাতে while, আর তুমি থামানো পর্যন্ত চালাতে break সহ loop, দরকার হলে break value দিয়ে একটা value বের করে আনো।

Practice

Objective: একটা for loop, value হিসেবে if, আর একটা counter একসাথে use করো।

Challenge: [420, 185, 150, 999, 60] দাম গুলোর ভেতর দিয়ে যাও। প্রতিটাকে label দাও premium (400 বা তার বেশি) অথবা regular, কয়টা premium গোনো, আর total যোগ করো। শেষে, total কমপক্ষে 1000 হলে delivery free (0), না হলে 60।

Expected result:

 420  premium
 185  regular
 150  regular
 999  premium
  60  regular
2 premium items, total 1814, delivery 0
Hint 1

Loop এর আগে দুইটা mut counter লাগবে: total আর premium।

Hint 2

Loop এর ভেতরে let label = if price >= 400 { "premium" } else { "regular" }; এক line এই text টা দিয়ে দেয়।

Hint 3

{price:>4} দাম টাকে 4 character এর মধ্যে ডান দিকে রাখে, তাই label গুলো এক লাইনে থাকে।

Solution
fn main() {
    let prices = [420, 185, 150, 999, 60];
    let mut total = 0;
    let mut premium = 0;

    for price in prices {
        let label = if price >= 400 { "premium" } else { "regular" };
        if price >= 400 {
            premium += 1;
        }
        total += price;
        println!("{price:>4}  {label}");
    }

    let delivery = if total >= 1_000 { 0 } else { 60 };
    println!("{premium} premium items, total {total}, delivery {delivery}");
}

Program টা price >= 400 দুইবার check করছে। আপাতত এটা ঠিক আছে। Pattern Matching with match জানার পর এক decision থেকেই label আর count দুটোই বের করার আরও পরিষ্কার উপায় দেখবে।

Station stamp

Chapter শেষ করো

পড়া শেষ হলে Complete চাপো, progress save হবে। XP শুধু Pro তে — Pro থাকলে এই chapter এ +10 XP পেতে।

Pro নিয়ে XP পাও →