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)?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With