What are some typical use cases requiring self-possession?

In the book Rust In the chapter "Method Syntax" there is an example of self-ownership:

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 some typical use cases requiring self-possession? Is this only when self is a value on the stack (where will it be copied)?

+4
source share
1 answer

Acceptance of ownership makes sense when an object is invalid by a method. Imagine a method Iterator.drop(u32)implemented as returning a new object instead of modifying an existing one. Calling additional methods on the source iterator will lead to inconsistencies.

Other examples of such annulment may be different types of wrappers.

+3
source

Source: https://habr.com/ru/post/1607312/


All Articles