← Back to Rust Course | Chapter 13: Smart Pointers & Unsafe | Lesson 1 of 7

Box Type का उपयोग

Box एक value को heap पर रखता है और आपको इसका एक simple handle देता है, जो बड़े या self-referencing data के लिए handy है।
Syntax
rust
let name = Box::new(value);
let value = *name;

enum List {
    Cons(i32, Box<List>),
    Nil,
}

Boxing a Value

Box::new(value) एक value को heap पर move करता है और इस पर point करता एक Box<T> return करता है। Box खुद stack पर रहता है और heap data को own करता है।

उदाहरण: Boxing a Value

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `boxed_number`, set to `Box::new(42)`
    let boxed_number = Box::new(42);
    // Print "Boxed value: {}" to the console, substituting in `boxed_number` (with a trailing newline)
    println!("Boxed value: {}", boxed_number);
}

Boxing a Recursive Type

Recursive types, जैसे एक साधारण linked list, indirection के बिना एक infinite size होता। Recursive field को Box में wrap करना इसे एक fixed, known size देता है, क्योंकि एक Box सिर्फ एक pointer है।

उदाहरण: Boxing a Recursive Type

markup
// Define an enum `List` listing its possible variants
enum List {
    Cons(i32, Box<List>),
    Nil,
}

// Bring `List::{Cons, Nil}` into scope
use List::{Cons, Nil};

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `list`, set to `Cons(1, Box::new(Cons(2, Box::new(Nil))))`
    let list = Cons(1, Box::new(Cons(2, Box::new(Nil))));
    // If `list` matches `Cons(value, _)`, bind and run this block
    if let Cons(value, _) = list {
        // Print "First value: {}" to the console, substituting in `value` (with a trailing newline)
        println!("First value: {}", value);
    }
}

Dereferencing a Box

* operator एक Box को dereference करता है, इसके रखे value को सीधे access देते हुए, बिल्कुल किसी और pointer-जैसे type को dereference करने की तरह।

उदाहरण: Dereferencing a Box

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `boxed`, set to `Box::new(10)`
    let boxed = Box::new(10);
    // Declare an immutable variable `doubled`, set to `*boxed * 2`
    let doubled = *boxed * 2;
    // Print "Doubled: {}" to the console, substituting in `doubled` (with a trailing newline)
    println!("Doubled: {}", doubled);
}

Box for Trait Objects

Box<dyn Trait> एक value store करने का एक आम तरीका है जिसका exact concrete type compile time पर पता नहीं, जब तक यह एक specific trait implement करे।

उदाहरण: Box for Trait Objects

markup
// Define a trait `Speak` describing shared behavior
trait Speak {
    // Define the function `say` taking `&self` and returning a `String;`
    fn say(&self) -> String;
}

// Define a struct `Dog` to group related fields together
struct Dog;

// Implement the `Speak` trait for `Dog`
impl Speak for Dog {
    // Define the function `say` taking `&self` and returning a String
    fn say(&self) -> String {
        String::from("Woof!")
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `animal` (a `Box<dyn Speak>`), set to `Box::new(Dog)`
    let animal: Box<dyn Speak> = Box::new(Dog);
    // Print "{}" to the console, substituting in `animal.say()` (with a trailing newline)
    println!("{}", animal.say());
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. Box<T> उपयोग करना जब कोई value stack पर पूरी तरह ठीक fit हो जाती, अनावश्यक heap allocation overhead जोड़ते हुए।
  2. यह भूल जाना कि एक recursive data type (जैसे एक linked list node) को एक known, finite size के लिए Box (या similar) चाहिए।
  3. यह मान लेना कि Box shared ownership allow करता है -- यह single-owner है, बिल्कुल किसी और owned value की तरह; sharing के लिए Rc उपयोग करें।
चैप्टर सारांश
  • Box<T> एक value को heap पर allocate करता है और इसे own करता है, आपको stack पर store करने के लिए एक fixed-size pointer देते हुए।
  • Box recursive types के लिए ज़रूरी है, क्योंकि इसके बिना compiler type के लिए एक finite size compute नहीं कर सकता था।
  • * से एक Box को dereference करना inner value को सीधे access देता है।
  • Box के पास single ownership semantics है, बिल्कुल दूसरी owned values की तरह -- यह अपने आप drop और free हो जाता है।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.