Methods और self
self बस यह है कि method कैसे उस struct को refer करता है जिससे यह attached है।In this page:
impl Name {
fn read(&self) {}
fn modify(&mut self) {}
fn consume(self) {}
}
Reading Data with &self
एक method जिसे सिर्फ struct की fields पढ़नी हैं वह &self लेता है, instance का एक immutable borrow। यह सबसे आम तरह का method है।
उदाहरण: Reading Data with &self
// Define a struct `Book` to group related fields together
struct Book {
title: String,
pages: u32,
}
// Implement methods on `Book`
impl Book {
// Define the function `summary` taking `&self` and returning a String
fn summary(&self) -> String {
format!("{} ({} pages)", self.title, self.pages)
}
}
// Entry point: execution of the program starts here
fn main() {
// Declare an immutable variable `book`, set to `Book { title: String::from("The Rust Book"), pages: 500 }`
let book = Book { title: String::from("The Rust Book"), pages: 500 };
// Print "{}" to the console, substituting in `book.summary()` (with a trailing newline)
println!("{}", book.summary());
}
Login to try C/C++/Java/PHP code in the editor
Modifying Data with &mut self
एक method जो struct की किसी field को बदलता है उसे &mut self लेना चाहिए, एक mutable borrow, और instance रखने वाले variable को खुद mut declare किया जाना चाहिए।
उदाहरण: Modifying Data with &mut self
// Define a struct `Counter` to group related fields together
struct Counter {
value: i32,
}
// Implement methods on `Counter`
impl Counter {
// Define the function `increment` taking `self`
fn increment(&mut self) {
self.value += 1;
}
}
// Entry point: execution of the program starts here
fn main() {
// Declare a mutable variable `counter`, initialized to `Counter { value: 0 }`
let mut counter = Counter { value: 0 };
counter.increment();
counter.increment();
// Print "Counter: {}" to the console, substituting in `counter.value` (with a trailing newline)
println!("Counter: {}", counter.value);
}
Login to try C/C++/Java/PHP code in the editor
Consuming self
एक method जो plain self (बिना & के) लेता है instance की पूरी ownership लेता है, इसे consume करते हुए। यह तब उपयोग होता है जब एक method किसी value को किसी और चीज़ में transform करता है और original को और उपयोग नहीं होना चाहिए।
उदाहरण: Consuming self
// Define a struct `Wrapper` to group related fields together
struct Wrapper {
value: String,
}
// Implement methods on `Wrapper`
impl Wrapper {
// Define the function `unwrap` taking `self` and returning a String
fn unwrap(self) -> String {
self.value
}
}
// Entry point: execution of the program starts here
fn main() {
// Declare an immutable variable `wrapped`, set to `Wrapper { value: String::from("inside") }`
let wrapped = Wrapper { value: String::from("inside") };
// Declare an immutable variable `inner`, set to `wrapped.unwrap()`
let inner = wrapped.unwrap();
// Print "{}" to the console, substituting in `inner` (with a trailing newline)
println!("{}", inner);
}
Login to try C/C++/Java/PHP code in the editor
Dot Syntax Handles Referencing Automatically
जब आप instance.method() call करते हैं, Rust अपने आप referencing या dereferencing की सही मात्रा insert करता है ताकि method के self parameter की उम्मीद से मेल खाए, इसलिए आपको शायद ही कभी (&instance).method() हाथ से लिखना पड़े।
उदाहरण: Dot Syntax Handles Referencing Automatically
// Define a struct `Temperature` to group related fields together
struct Temperature {
celsius: f64,
}
// Implement methods on `Temperature`
impl Temperature {
// Define the function `to_fahrenheit` taking `&self` and returning a floating-point number
fn to_fahrenheit(&self) -> f64 {
self.celsius * 9.0 / 5.0 + 32.0
}
}
// Entry point: execution of the program starts here
fn main() {
// Declare an immutable variable `temp`, set to `Temperature { celsius: 20.0 }`
let temp = Temperature { celsius: 20.0 };
// Print "{}F" to the console, substituting in `temp.to_fahrenheit()` (with a trailing newline)
println!("{}F", temp.to_fahrenheit());
}
Login to try C/C++/Java/PHP code in the editor
&selfका मतलब होने परselfलिखना, जो struct को method में move कर देगा बजाय इसे सिर्फ borrow करने के।- यह भूल जाना कि
&mut selfकिसी भी method के लिए ज़रूरी है जो struct की अपनी किसी field को modify करता है। - किसी method को
Type::method(instance)के रूप में call करना जब simplerinstance.method()dot-call syntax ज़्यादा clear और idiomatic है।
&selfinstance को immutably borrow करता है, एक method को अपनी fields पढ़ने देते हुए बिना ownership लिए।&mut selfinstance को mutably borrow करता है, एक method को अपनी fields modify करने देते हुए।- Plain
self(बिना&के) instance की ownership लेता है, इसे consume करते हुए -- कम बार उपयोग होता है, आमतौर पर conversions के लिए। - Dot-call syntax
instance.method()अपने आपselfके लिए referencing/dereferencing handle करता है।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: