Part 01 · Rust Is Not Scary

The Compiler Is Your Teacher

Error messageshelp: linesrustc --explain

Rust এর error line ধরে ধরে কীভাবে পড়বে। বেশিরভাগ সময় fix টা compiler নিজেই লিখে দেয়।

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

The story

জীবনের সবচেয়ে ভালো teacher এর কথা মনে করো। Homework এ শুধু একটা লাল ক্রস দিয়ে ছেড়ে দিতেন না। ঠিক কোন line টা ভুল সেটা গোল করে দিতেন, পাশে লিখে দিতেন কেন ভুল, আর প্রায়ই পাশে ঠিক answer টাও লিখে দিতেন।

Rust এর compiler ঠিক ওই teacher এর মতো তোমার কাজ দেখে দেয়। Rust এর প্রথম সপ্তাহ বেশিরভাগ মানুষের কাছে মনে হয় error message এর বকা খাওয়া। কিন্তু পড়তে জানলে বোঝা যায়, mainstream language গুলোর মধ্যে এগুলোই সবচেয়ে কাজের error message: কী ভুল বলে, ঠিক কোন character গুলো দেখিয়ে দেয়, আর অনেক সময় fix টাও লিখে দেয়। এই lesson এ এগুলো পড়তে শিখবে, যাতে course এর বাকিটা মারামারি না, আলাপের মতো লাগে।

The idea

প্রতিটা Rust error এর একই পাঁচটা অংশ থাকে। কোন অংশ কোথায় জানলে লম্বা error ও এক নজরে পড়া যায়:

1. what went wrong (error code)2. where: file, line, column3. your code; ^^^ marks the problem4. help: the fix, + shows what to add5. the long explanationerror[E0384]: cannot assign twice to immutable variable `total` --> src/main.rs:10:9 8 | let total = 0; | ----- first assignment to `total`10 | total += price; | ^^^^^^^^^^^^^^ cannot assign twicehelp: consider making this binding mutable 8 | let mut total = 0; | +++For more information about this error, try `rustc --explain E0384`.read the first error first: fixing it often fixes or reveals the rest
একটা Rust error এর পাঁচ অংশ: error code সহ কী ভুল হয়েছে, কোথায় (file, line, column), তোমার code যেখানে problem এর নিচে ^^^ আর related জায়গার নিচে ---, fix সহ help, আর লম্বা explanation কীভাবে পাবে।
  1. কী ভুল হয়েছে: error[E0384]: cannot assign twice to immutable variable `total` । E0384 হলো error টার ID। পরের কথাগুলো এক line এর summary।
  2. কোথায়: --> src/main.rs:10:9 মানে file, line 10, column 9। বেশিরভাগ editor আর terminal এ এটায় click করা যায়।
  3. তোমার code, দাগ দেওয়া: যে line গুলো জড়িত, আসল problem এর নিচে ^^^^, আর related জায়গার নিচে ---- (এখানে, যেখানে total প্রথম set হয়েছিল)।
  4. help: suggest করা fix, প্রায়ই ঠিক করা line হিসেবে। যা add করতে হবে তার নিচে +, যা মুছতে হবে তার নিচে -।
  5. লম্বা version: rustc --explain E0384 example সহ পুরো explanation print করে।

সব error এ সব অংশ থাকে না, কিন্তু যেগুলো থাকে সেগুলো এই order এই আসে। এছাড়া আছে note: line, যেগুলো background দেয় ("এজন্য এমন")। আর আছে warning, যেগুলোর shape একই, কিন্তু শুরু হয় warning: দিয়ে আর build থামায় না।

Try it: fix a program in three rounds

এখানে তিনটা ভুল সহ একটা ছোট program। Cart এর দাম যোগ করে delivery যোগ করার কথা:

fn total_with_delivery(total: u64) -> u64 {
    let delivery = if total >= 100_000 { 0 } else { 6_000 };
    total + delivery;
}

fn main() {
    let prices = [42_000, 18_550, 15_000];
    let total = 0;
    for price in prices {
        total += price;
    }
    println!("to pay: {}", total_with_delivery(totl));
}

Round 1। cargo check চালাও:

error[E0425]: cannot find value `totl` in this scope
  --> src/main.rs:12:48
   |
12 |     println!("to pay: {}", total_with_delivery(totl));
   |                                                ^^^^
   |
help: a local variable with a similar name exists
   |
12 |     println!("to pay: {}", total_with_delivery(total));
   |                                                   +

error[E0308]: mismatched types
 --> src/main.rs:1:39
  |
1 | fn total_with_delivery(total: u64) -> u64 {
  |    -------------------                ^^^ expected `u64`, found `()`
  |    |
  |    implicitly returns `()` as its body has no tail or `return` expression
2 |     let delivery = if total >= 100_000 { 0 } else { 6_000 };
3 |     total + delivery;
  |                     - help: remove this semicolon to return this value

Some errors have detailed explanations: E0308, E0425.
For more information about an error, try `rustc --explain E0308`.
error: could not compile `bill` (bin "bill") due to 2 previous errors

দুইটা error। একটা একটা করে, উপর থেকে ধরো:

  • E0425: totl বলে কিছু নেই। Help line টা typo ধরে ফেলেছে: "a local variable with a similar name exists", আর total দেখাচ্ছে, যে অক্ষর টা নেই তার নিচে একটা +।
  • E0308: function এর শেষ line এ semicolon, Functions lesson এর সেই ভুল।

শুধু typo টা ঠিক করো, আবার check করো।

আগে অনুমান করো

totl ঠিক করলে। আগে 2 টা error ছিল। এখন cargo check কয়টা দেখাবে?

error[E0308]: mismatched types
 --> src/main.rs:1:39
  |
1 | fn total_with_delivery(total: u64) -> u64 {
  |    -------------------                ^^^ expected `u64`, found `()`
  |    |
  |    implicitly returns `()` as its body has no tail or `return` expression
2 |     let delivery = if total >= 100_000 { 0 } else { 6_000 };
3 |     total + delivery;
  |                     - help: remove this semicolon to return this value

error[E0384]: cannot assign twice to immutable variable `total`
  --> src/main.rs:10:9
   |
 8 |     let total = 0;
   |         ----- first assignment to `total`
 9 |     for price in prices {
10 |         total += price;
   |         ^^^^^^^^^^^^^^ cannot assign twice to immutable variable
   |
help: consider making this binding mutable
   |
 8 |     let mut total = 0;
   |         +++

Some errors have detailed explanations: E0308, E0384.
For more information about an error, try `rustc --explain E0308`.
error: could not compile `bill` (bin "bill") due to 2 previous errors

এখনো দুইটা, আর একটা নতুন: E0384, mut ছাড়া total বদলানো। প্রথমবার এটা সবাইকে অবাক করে। তোমার fix কিছু ভেঙে দেয়নি। Compiler কয়েকটা stage এ কাজ করে: আগে check করে সব নাম আছে কিনা, তারপর type, তারপর কে কী বদলাচ্ছে (borrow checker)। আগের stage pass না করলে পরের stage চালাতে পারে না। তাই তুমি আসলে এগোচ্ছ, অথচ error এর সংখ্যা একই থাকতে পারে, এমনকি বাড়তেও পারে।

Round 2: semicolon টা মুছে দাও।

error[E0384]: cannot assign twice to immutable variable `total`
  --> src/main.rs:10:9
   |
 8 |     let total = 0;
   |         ----- first assignment to `total`
 9 |     for price in prices {
10 |         total += price;
   |         ^^^^^^^^^^^^^^ cannot assign twice to immutable variable
   |
help: consider making this binding mutable
   |
 8 |     let mut total = 0;
   |         +++

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

Round 3: mut add করো, ঠিক যেখানে +++ দেখাচ্ছে।

    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.03s
to pay: 81550

শূন্য error, আর program চলছে: ৳755.50 এর বাজার আর ৳60 delivery মিলে 81,550 paisa (৳815.50)। খেয়াল করো কী করলে: তিনটা fix, আর একবারও আন্দাজ করতে হয়নি। প্রতিটা একটা help: line এ লেখা ছিল।

What the compiler says

এক line এর summary এর চেয়ে বেশি চাও? লম্বা version টা চেয়ে নাও:

rustc --explain E0384

Page টা Markdown এ লেখা। এখানে ``` fence line গুলো বাদ দিয়ে দেখানো হলো:

An immutable variable was reassigned.

Erroneous code example:

fn main() {
    let x = 3;
    x = 5; // error, reassignment of immutable variable
}

By default, variables in Rust are immutable. To fix this error, add the keyword
`mut` after the keyword `let` when declaring the variable. For example:

fn main() {
    let mut x = 3;
    x = 5;
}

Alternatively, you might consider initializing a new variable: either with a new
bound name or (by [shadowing]) with the bound name of your existing variable.
For example:

[shadowing]: https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#shadowing

fn main() {
    let x = 3;
    let x = 5;
}

প্রতিটা error code এর এমন একটা page আছে: error টার মানে কী, কোন ছোট example এ এটা হয়, আর সাধারণত কীভাবে ঠিক করে। খেয়াল করো E0384 এর জন্য দুইটা fix দিচ্ছে: mut add করো, অথবা shadowing দিয়ে নতুন variable বানাও। ছোট help: line শুধু প্রথমটা দেখিয়েছিল। Suggest করা fix টা তোমার code এর জন্য ঠিক না মনে হলে, বাকি option গুলোর জন্য --explain দেখো। একই page গুলো online এও আছে, Rust error code index এ।

আর code compile হয়ে গেলেও, দ্বিতীয় একজন teacher সাহায্য করতে পারে। Clippy হলো Rust এর official linter: এমন কয়েকশো pattern চেনে যেগুলো কাজ করে, কিন্তু আরও পরিষ্কার বা Rust এর চলতি style এ লেখার উপায় আছে। চালাও cargo clippy দিয়ে:

fn main() {
    let rating = 4;
    let in_stock = true;
    if rating >= 1 && rating <= 5 {
        println!("valid rating");
    }
    if in_stock == true {
        println!("show the Buy button");
    }
}
warning: manual `RangeInclusive::contains` implementation
 --> src/main.rs:4:8
  |
4 |     if rating >= 1 && rating <= 5 {
  |        ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `(1..=5).contains(&rating)`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.98.0/index.html#manual_range_contains
  = note: `#[warn(clippy::manual_range_contains)]` on by default

warning: equality checks against true are unnecessary
 --> src/main.rs:7:8
  |
7 |     if in_stock == true {
  |        ^^^^^^^^^^^^^^^^ help: try: `in_stock`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.98.0/index.html#bool_comparison
  = note: `#[warn(clippy::bool_comparison)]` on by default

warning: `lint` (bin "lint") generated 2 warnings (run `cargo clippy --fix --bin "lint" -p lint -- ` to apply 2 suggestions)

দুইটাই warning, error না: code ঠিকই ছিল। Clippy style শেখাচ্ছে: (1..=5).contains(&rating) পড়লে মনে হয় "rating 1 থেকে 5 এর মধ্যে", আর if in_stock == true এর চেয়ে if in_stock বেশি পরিষ্কার। শেষ line এ এমনকি cargo clippy --fix দিচ্ছে, যাতে suggestion গুলো তোমার হয়ে বসিয়ে দেয়। Experienced Rust developer রা কীভাবে লেখে সেটা শেখার সবচেয়ে fast উপায়গুলোর একটা হলো নিয়মিত Clippy চালানো।

Under the hood

Rust এর error এত ভালো কেন? কিছুটা এই কারণে যে compiler কে অনেক কিছু জানতে হয়: ownership আর borrowing check করতে ও track করে প্রতিটা value কোথায় তৈরি হলো, কোথায় move হলো, borrow হলো, বদলাল। কিছু ভুল হলে explain করার সব তথ্য ওর হাতে আগে থেকেই থাকে, জড়িত অন্য জায়গাটা সহ (---- line টা)।

আর এটা ইচ্ছা করেই। Rust project একটা confusing error message কে bug হিসেবে ধরে। মানুষ অস্পষ্ট error নিয়ে issue খোলে, আর সেগুলো fix হয়। "a local variable with a similar name exists" hint টা ওই কাজেরই ফল।

কয়েকটা habit যেগুলো তোমাকে fast বানাবে:

  • প্রথম error টা আগে পড়ো। পরের error গুলো প্রায়ই আগেরটার কারণে আসে। উপরেরটা ঠিক করো, আবার cargo check চালাও, এভাবে চলতে থাকো।
  • Error ঠিক করার সময় cargo run না, cargo check। Program বানানোর step টা skip করে, তাই তাড়াতাড়ি answer দেয়।
  • Editor কে করতে দাও। rust-analyzer type করার সময়ই একই error গুলো line এর পাশে দেখায়, আর বেশিরভাগ help: suggestion এক click এর quick fix হিসেবে পাওয়া যায়।
  • help: line পড়ো, তারপর ভাবো। সাধারণত ঠিকই থাকে। যখন থাকে না (যেমন Why Rust Feels Hard এ অচেনা coupon এর জন্য expect), তখনও বলে দেয় compiler এর কী লাগবে। কীভাবে সেটা দেবে, decide করো তুমি।

Compared with other languages

একই typo (totl) Python আর Go তে। Python এ, এমন একটা code path এ যেটা শুধু কিছু order নেয়:

def checkout(total):
    if total >= 100_000:
        return total
    return totl + 6_000  # typo, only on the path with a delivery fee

print(checkout(150_000))  # free delivery: works
print(checkout(81_550))   # pays delivery: crashes
150000
Traceback (most recent call last):
NameError: name 'totl' is not defined. Did you mean: 'total'?

Python এর message ও কাজের ("Did you mean: 'total'?"), কিন্তু খেয়াল করো কখন আসে। প্রথম order ঠিকঠাক চলেছে। শুধু যে order delivery দেয়, সেটাই typo ওয়ালা line চালায়। তোমার test যদি শুধু বড় order দিয়ে হয়ে থাকে, এটা production এ চলে যাবে।

package main

import "fmt"

func checkout(total uint64) uint64 {
	if total >= 100_000 {
		return total
	}
	return totl + 6_000 // typo
}

func main() {
	fmt.Println(checkout(81_550))
}
# command-line-arguments
./main.go:9:9: undefined: totl

Go run এর আগেই ধরে, ছোট একটা message দিয়ে: কী আর কোথায়, কোনো suggestion নেই।

PythonGoRust
নামে typoওই line চললে NameErrorcompile errorcompile error
ঠিক character গুলো দেখায়হ্যাঁ (^^^)line আর columnহ্যাঁ, সাথে related জায়গা (---)
Fix suggest করেমাঝে মাঝে ("Did you mean")কমইসাধারণত (ঠিক করা line সহ help:)
প্রতিটা error এর লম্বা explanationনানাrustc --explain E....
Style teacherlinter (ruff, pylint)go vet, staticcheckcargo clippy

Key takeaway

প্রতিটা Rust error এর shape একই: কী (error[E....] আর একটা summary), কোথায় (--> file:line:column), problem এর নিচে ^^^ সহ তোমার code, fix সহ help, আর লম্বা version এর জন্য rustc --explain। প্রথম error আগে ঠিক করো, আবার cargo check চালাও। Compiler stage এ stage এ কাজ করে, তাই একটা error ঠিক করলে পরেরটা বের হতে পারে, আর সেটা পিছিয়ে পড়া না, এগোনো। Code compile হয়ে গেলে cargo clippy আরও ভালো style শেখাতে থাকে।

Practice

Objective: শুধু compiler যা বলে তা দিয়েই একটা ভাঙা program ঠিক করো।

Challenge: এই program এর পাঁচটা rating এর average print করার কথা। এতে তিনটা ভুল আছে। cargo check চালাও, প্রথম error ঠিক করো, আবার চালাও, build না হওয়া পর্যন্ত এভাবে চলো। Compiler এখনো দেখায়নি এমন কিছু ঠিক কোরো না।

fn average(total: u64, count: u64) -> u64 {
    total / count;
}

fn main() {
    let ratings = [5, 4, 4, 3, 5];
    let sum = 0;
    for r in ratings {
        sum += r;
    }
    let avg = average(sum, ratings.len());
    println!("average rating: {avg}");
}

Expected result:

average rating: 4
Hint 1

প্রথম E0308 function টা দেখাচ্ছে: এমন একটা semicolon খোঁজো যেটা থাকার কথা না।

Hint 2

দ্বিতীয় E0308 বলছে u64 আশা করেছিল, পেয়েছে usize। ratings.len() দেয় একটা usize (size আর position এর জন্য Rust যে type use করে)। ratings.len() as u64 দিয়ে convert করো।

Hint 3

দুইটা type error চলে গেলে তৃতীয় একটা error আসবে, যেটা আগে ছিল না। এই lesson এই দেখেছ: কিছু একটা mut ছাড়াই বদলাচ্ছে।

Solution
fn average(total: u64, count: u64) -> u64 {
    total / count
}

fn main() {
    let ratings = [5, 4, 4, 3, 5];
    let mut sum = 0;
    for r in ratings {
        sum += r;
    }
    let avg = average(sum, ratings.len() as u64);
    println!("average rating: {avg}");
}

5, 4, 4, 3, 5 এর average 4.2, কিন্তু পূর্ণ সংখ্যার ভাগ দেয় 4। 4.2 চাইলে average কে f64 return করাও, আর ভাগ করো total as f64 / count as f64। আবার সেই Numbers, Text and Booleans।

Station stamp

Chapter শেষ করো

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

Pro নিয়ে XP পাও →