Rust-এ Structs & Enums সহজভাবে

A self-motivated and enthusiastic web developer with a deep interest in JavaScript (React.js). To work in the Software industry with modern web technologies of different local & multinational Software/ IT agencies of Bangladesh and grow rapidly with increasing responsibilities.
Rust একটি memory safe এবং performance oriented language। এখানে আমরা data organize করার জন্য মূলত দুইটি structure ব্যবহার করি:
Structs – Data group করা
Enums – Different types বা states represent করা
১️ Structs – Data group করা
Structs হলো Rust-এ এমন একটি structure যা বিভিন্ন ধরনের value একত্রে রাখে।
উদাহরণ:
struct Person {
name: String,
age: u32,
}
fn main() {
let person = Person {
name: String::from("Munna"),
age: 25,
};
println!("Name: {}, Age: {}", person.name, person.age);
}
struct Person→ একটি custom type declare করা হলো।nameএবংage→ এর field।Person { ... }→ struct এর instance বানানো।Access করতে →
person.nameবাperson.age।
কেন ব্যবহার করি:
Related data এক জায়গায় group করতে
Code readable ও organized রাখতে
Struct type:
Classic struct: যেমন উপরের উদাহরণ
Tuple struct: positional field, নাম নেই
struct Color(u8, u8, u8);
let black = Color(0, 0, 0);
println!("Black RGB: {}, {}, {}", black.0, black.1, black.2);
২️ Enums – Different types বা states
Enums হলো এমন একটি type যা বিভিন্ন state বা variant represent করে।
উদাহরণ:
enum Direction {
Up,
Down,
Left,
Right,
}
fn move_player(dir: Direction) {
match dir {
Direction::Up => println!("Moving Up"),
Direction::Down => println!("Moving Down"),
Direction::Left => println!("Moving Left"),
Direction::Right => println!("Moving Right"),
}
}
fn main() {
let player_dir = Direction::Left;
move_player(player_dir);
}
enum Direction→ type declare করা হলো যা ৪টি variant থাকতে পারে।matchব্যবহার করে সব variant handle করতে হয়।Rust compile-time-এ check করে যদি কোনো variant বাদ পড়ে, compile error দেয়।
Enums এর সুবিধা:
Different state safe way handle করতে
Option<T>বাResult<T,E>Rust এ enums-এর উপর তৈরি।
Enums + Data:
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
}
fn main() {
let msg = Message::Move { x: 10, y: 20 };
match msg {
Message::Quit => println!("Quit"),
Message::Move { x, y } => println!("Move to ({}, {})", x, y),
Message::Write(text) => println!("Write: {}", text),
}
}
এখানে enum variant data hold করতে পারে।
Struct এর মতো, enum variant এর data access করতে match ব্যবহার করতে হয়।
Struct: এক ধরনের data কে logically group করতে
Enum: একাধিক variant বা state represent করতে
Struct + Enum একসাথে ব্যবহার করলে Rust এ complex data model খুব clean ভাবে design করা যায়
Rust compile-time-এ safety check করে, runtime crash বা invalid memory access হয় না




