RicardasSim

Self, &self, &mut self, and self in Rust

Nov 14th, 2026
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 2.16 KB | None | 0 0
  1. /// Represents a simple pair of two `u8` values.
  2. /// Used to demonstrate `Self`, `&self`, `&mut self`, and `self` in Rust.
  3. struct Pair {
  4.     first: u8,
  5.     second: u8,
  6. }
  7.  
  8. impl Pair {
  9.     /// Creates a new `Pair` instance with default values.
  10.     /// Uses `Self` as an alias for the `Pair` type.
  11.     fn new() -> Self {
  12.         Self {
  13.             first: 100,
  14.             second: 123,
  15.         }
  16.     }
  17.  
  18.     /// Prints the current values without modifying them.
  19.     /// Uses `&self` to immutably borrow the instance.
  20.     fn print(&self) {
  21.         println!("first: {}", self.first);
  22.         println!("second: {}", self.second);
  23.     }
  24.  
  25.     /// Updates the `first` value.
  26.     /// Uses `&mut self` to mutably borrow and modify the instance.
  27.     fn set_first(&mut self, value: u8) {
  28.         self.first = value;
  29.     }
  30.  
  31.     /// Updates the `second` value.
  32.     /// Uses `&mut self` to mutably borrow and modify the instance.
  33.     fn set_second(&mut self, value: u8) {
  34.         self.second = value;
  35.     }
  36.  
  37.     /// Updates both values at once.
  38.     /// Uses `&mut self` to mutably borrow and modify the instance.
  39.     fn set_both(&mut self, first: u8, second: u8) {
  40.         self.first = first;
  41.         self.second = second;
  42.     }
  43.  
  44.     /// Consumes and drops the `Pair` instance.
  45.     /// Uses `self` to take ownership; the instance cannot be used after calling this.
  46.     fn consume(self) {
  47.         println!(
  48.             "Consuming pair -> first: {}, second: {}",
  49.             self.first, self.second
  50.         );
  51.     }
  52. }
  53.  
  54. fn main() {
  55.     // Initialize a mutable instance using the `Self` constructor
  56.     let mut pair = Pair::new();
  57.  
  58.     println!("--(1)-----------");
  59.     pair.print(); // Immutable borrow (&self)
  60.  
  61.     // Modify fields using mutable borrows (&mut self)
  62.     pair.set_first(71);
  63.     pair.set_second(72);
  64.  
  65.     println!("--(2)-----------");
  66.     pair.print();
  67.  
  68.     pair.set_both(17, 27);
  69.  
  70.     println!("--(3)-----------");
  71.     pair.print();
  72.  
  73.     println!("--(4)-----------");
  74.     pair.consume(); // Ownership moved (self); `pair` is dropped here
  75.  
  76.     // Compile-time error if uncommented: borrow of moved value: `pair`
  77.     // pair.print();
  78. }
  79.  
Advertisement
Add Comment
Please, Sign In to add comment