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

Unsafe के Basics

unsafe एक special zone है जहां Rust आप पर भरोसा करता है कि आप खुद safety rules follow करेंगे, क्योंकि यह वहां सब कुछ जांच नहीं सकता।
Syntax
rust
unsafe {
    // operations the compiler cannot verify
}

unsafe fn name() {}

What unsafe Unlocks

एक unsafe block extra operations का एक छोटा set allow करता है, जैसे raw pointers dereference करना या unsafe functions call करना, जिन्हें compiler खुद पूरी तरह verify नहीं कर सकता कि सुरक्षित हैं।

उदाहरण: What unsafe Unlocks

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `value`, set to `10`
    let value = 10;
    // Declare an immutable variable `raw_pointer`, set to `&value as *const i32`
    let raw_pointer = &value as *const i32;
    unsafe {
        // Print "Value through raw pointer: {}" to the console, substituting in `*raw_pointer` (with a trailing newline)
        println!("Value through raw pointer: {}", *raw_pointer);
    }
}

Calling an Unsafe Function

unsafe fn से चिह्नित Functions सिर्फ एक unsafe block के अंदर से call किए जा सकते हैं, यह signal करते हुए कि caller को कुछ safety guarantees बनाए रखनी चाहिए जिन पर function भरोसा करता है।

उदाहरण: Calling an Unsafe Function

markup
unsafe fn dangerous_operation() -> i32 {
    42
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `result`, set to `unsafe { dangerous_operation() }`
    let result = unsafe { dangerous_operation() };
    // Print "Result: {}" to the console, substituting in `result` (with a trailing newline)
    println!("Result: {}", result);
}

Safe Rust Still Applies Around unsafe

किसी unsafe block के बाहर का code, और यहां तक कि इसके अंदर का ज़्यादातर code, अब भी Rust के सभी normal type checking और ownership rules follow करता है -- unsafe सिर्फ कुछ specific restrictions हटाता है।

उदाहरण: Safe Rust Still Applies Around unsafe

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare a mutable variable `value`, initialized to `5`
    let mut value = 5;
    {
        // Declare an immutable variable `pointer`, set to `&mut value as *mut i32`
        let pointer = &mut value as *mut i32;
        unsafe {
            *pointer += 10;
        }
    }
    // Print "value = {}" to the console, substituting in `value` (with a trailing newline)
    println!("value = {}", value);
}

Wrapping unsafe in a Safe API

एक आम pattern unsafe code को छोटा और private रखना है, सिर्फ एक safe public function expose करते हुए जो internally unsafe operation उपयोग करने से पहले इसकी preconditions पूरी होने की गारंटी देता है।

उदाहरण: Wrapping unsafe in a Safe API

markup
// Define the function `safe_get` taking `arr`, `index` and returning a `Option<i32>`
fn safe_get(arr: &[i32], index: usize) -> Option<i32> {
    // Check whether `index < arr.len()`
    if index < arr.len() {
        Some(unsafe { *arr.get_unchecked(index) })
    // Otherwise, run this branch
    } else {
        None
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `data`, set to `[1, 2, 3]`
    let data = [1, 2, 3];
    // Print "{:?}" to the console, substituting in `safe_get(&data, 1)` (with a trailing newline)
    println!("{:?}", safe_get(&data, 1));
    // Print "{:?}" to the console, substituting in `safe_get(&data, 10)` (with a trailing newline)
    println!("{:?}", safe_get(&data, 10));
}
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. एक साधारण borrow-checker error ठीक करने के लिए unsafe तक पहुंचना, जब असली fix लगभग हमेशा safe code को restructure करना है।
  2. यह मान लेना कि unsafe Rust की सभी checks बंद कर देता है -- यह सिर्फ extra abilities का एक छोटा specific set unlock करता है, जैसे raw pointers dereference करना।
  3. एक बड़ा unsafe block लिखना जब असल में सिर्फ एक specific line को extra capability चाहिए, इसे audit करना मुश्किल बनाते हुए।
चैप्टर सारांश
  • unsafe blocks extra abilities का एक छोटा set unlock करते हैं जो safe Rust में allowed नहीं, जैसे raw pointers dereference करना।
  • unsafe उपयोग करना code में बाकी जगह borrow checker या type checking को disable नहीं करता।
  • Safe abstractions अक्सर एक छोटे unsafe core के आस-पास बनाए जाते हैं, callers को पूरी तरह safe API expose करते हुए।
  • unsafe को sparingly उपयोग किया जाना चाहिए और manual review आसान बनाने के लिए जितना संभव हो छोटा रखना चाहिए।
🔒

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.