References aur Borrowing
Ek reference aapko ownership liye baghair ek value istemal 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()
}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 ijazat deta hai, lekin ek ahem restriction ke sath: ek waqt 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");
}hello, world
Ek real borrow conflict kaisa dikhta hai
Yeh waqai woh hai jo rustc report karta hai jab aap ek mutable reference banane ki koshish karte hain jab ek immutable reference abhi bhi istemal 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);
}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`.Yehi 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, kyunke 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 likhein jo s.split_whitespace().count() istemal kar ke s mein words ki ginti wapas kare. Use "the quick brown fox" wale ek String ke reference ke sath call karein aur result print karein.