Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// Represents a simple pair of two `u8` values.
- /// Used to demonstrate `Self`, `&self`, `&mut self`, and `self` in Rust.
- struct Pair {
- first: u8,
- second: u8,
- }
- impl Pair {
- /// Creates a new `Pair` instance with default values.
- /// Uses `Self` as an alias for the `Pair` type.
- fn new() -> Self {
- Self {
- first: 100,
- second: 123,
- }
- }
- /// Prints the current values without modifying them.
- /// Uses `&self` to immutably borrow the instance.
- fn print(&self) {
- println!("first: {}", self.first);
- println!("second: {}", self.second);
- }
- /// Updates the `first` value.
- /// Uses `&mut self` to mutably borrow and modify the instance.
- fn set_first(&mut self, value: u8) {
- self.first = value;
- }
- /// Updates the `second` value.
- /// Uses `&mut self` to mutably borrow and modify the instance.
- fn set_second(&mut self, value: u8) {
- self.second = value;
- }
- /// Updates both values at once.
- /// Uses `&mut self` to mutably borrow and modify the instance.
- fn set_both(&mut self, first: u8, second: u8) {
- self.first = first;
- self.second = second;
- }
- /// Consumes and drops the `Pair` instance.
- /// Uses `self` to take ownership; the instance cannot be used after calling this.
- fn consume(self) {
- println!(
- "Consuming pair -> first: {}, second: {}",
- self.first, self.second
- );
- }
- }
- fn main() {
- // Initialize a mutable instance using the `Self` constructor
- let mut pair = Pair::new();
- println!("--(1)-----------");
- pair.print(); // Immutable borrow (&self)
- // Modify fields using mutable borrows (&mut self)
- pair.set_first(71);
- pair.set_second(72);
- println!("--(2)-----------");
- pair.print();
- pair.set_both(17, 27);
- println!("--(3)-----------");
- pair.print();
- println!("--(4)-----------");
- pair.consume(); // Ownership moved (self); `pair` is dropped here
- // Compile-time error if uncommented: borrow of moved value: `pair`
- // pair.print();
- }
Advertisement