Ownership और Borrowing

Rust References and Borrowing

Let a function use a value without taking it: & to read, &mut to change.

  • मध्यम
  • 3 मिनट में पढ़ें
  • 1 चलाने योग्य उदाहरण
आप क्या सीखेंगे
  • & and &mut
  • Borrowing in function calls
  • Many readers or one writer
Borrow → what it allows
length(&message)read only
add_exclamation(&mut message)can change it
let first = &messagemany readers are fine

Use a value without owning it

A reference lets code use a value without owning it. This is called borrowing. &value borrows for reading and &mut value borrows for changing.

length only reads the text, so it takes &str and message can still be used afterwards. add_exclamation needs &mut String to change it. Rust allows many readers at once or one writer, but never both, which rules out data races at compile time.

मुख्य बातें

  1. &value borrows for reading.
  2. &mut value borrows for changing.
  3. Many readers or one writer, never both.

चलने योग्य Rust उदाहरण

Rust
कोड चलाएँ →
main.rs
fn length(text: &str) -> usize {
    text.len()
}

fn add_exclamation(text: &mut String) {
    text.push('!');
}

fn main() {
    let mut message = String::from("Borrow me");

    let size = length(&message); // immutable borrow
    println!("{message} has {size} bytes");

    add_exclamation(&mut message); // mutable borrow
    println!("{message}");

    let first = &message;
    let second = &message; // many readers are fine
    println!("{first} {second}");
}
इस उदाहरण के लिए Run बटन बनाएँ कोड चलाने का परिणाम
Borrow me has 9 bytes
Borrow me!
Borrow me! Borrow me!

अभ्यास

उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।

यह पाठ पूरा कर लिया?

अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।

अगला: Slices →

चैलेंज से अभ्यास करें

इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।

सभी चैलेंज