AnyCompiler

References aur Borrowing

Ek reference aapko ownership liye bina ek value use karne deta hai — & se likha jaata hai. Original owner value ko rakhta hai, aur reference sirf temporarily usko access karne ke liye borrow karta hai.

fn main() {
    let s1 = String::from("hello");
    let len = calculate_length(&s1);

    println!("The length of '{}' is {}.", s1, len);
}

fn calculate_length(s: &String) -> usize {
    s.len()
}
Output
The length of 'hello' is 5.

calculate_length, s1 ki ownership lene ke bajaye use ek reference ke through borrow karta hai, isliye call ke baad main mein s1 abhi bhi perfectly usable hai.

Mutable references

Ek mutable reference, &mut T, ek function ko us value ko modify karne deta hai jise woh borrow karta hai. Rust ise allow karta hai, lekin ek crucial restriction ke sath: ek time par aapke paas ek value ke liye ya to ek mutable reference ho sakta hai, ya kitne bhi immutable references ho sakte hain — dono kabhi nahi.

fn main() {
    let mut s = String::from("hello");
    change(&mut s);
    println!("{}", s);
}

fn change(s: &mut String) {
    s.push_str(", world");
}
Output
hello, world

Ek real borrow conflict kaisa dikhta hai

Yeh genuinely woh hai jo rustc report karta hai jab aap ek mutable reference banane ki koshish karte ho jab ek immutable reference abhi bhi use mein ho — ek real run se capture kiya gaya hai, plausible dikhne ke liye likha nahi gaya:

fn main() {
    let mut s = String::from("hello");

    let r1 = &s;
    let r2 = &mut s;

    println!("{}, {}", r1, r2);
}
Output
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
 --> main.rs:5:14
  |
4 |     let r1 = &s;
  |              -- immutable borrow occurs here
5 |     let r2 = &mut s;
  |              ^^^^^^ mutable borrow occurs here
6 | 
7 |     println!("{}, {}", r1, r2);
  |                        -- immutable borrow later used here

error: aborting due to previous error

For more information about this error, try `rustc --explain E0502`.

Yahi rule hai jo data races ko poori tarah rule out kar deta hai, compile time par hi — program ke do parts kabhi bhi same data ko ek saath read aur write nahi kar sakte, kyunki compiler us code ko compile hone hi nahi dega jo yeh hone deta.

Aage: strings aur slices — ek owned String aur ek borrowed &str mein kya farq hai.

Practice Exercise

Ek function word_count(s: &String) -> usize likho jo s.split_whitespace().count() use karke s mein words ki ginti return kare. Use "the quick brown fox" wale ek String ke reference ke sath call karo aur result print karo.