Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the typical use cases that require taking ownership of self?

Tags:

rust

In the Rust book Method Syntax chapter, there's an example of taking ownership of self:

struct Circle {
    x: f64,
    y: f64,
    radius: f64,
}

impl Circle {
    fn reference(&self) {
        println!("taking self by reference!");
    }

   fn mutable_reference(&mut self) {
       println!("taking self by mutable reference!");
   }

   fn takes_ownership(self) {
      println!("taking ownership of self!");
   }
}

What are the typical use cases that require taking ownership of self? Is it only when self is a value on the stack (where it will be copied)?

like image 961
NXH Avatar asked Sep 27 '22 18:09

NXH


1 Answers

Taking ownership makes sense when the object is invalidated by the method. Imagine a method Iterator.drop(u32), implemented as returning a new object instead of modifying the existing one. Calling additional methods on the original iterator would lead to inconsistencies.

Other examples for such invalidation would be different sorts of wrappers.

like image 64
Silly Freak Avatar answered Oct 11 '22 16:10

Silly Freak