Rookie 'self' ownership question?

This code fails if I call anything after the steal_ownership_fuction() function.
Can you guys tell me why? Why does that simple print function break things? I am super new to rust, sorry if its a odd question.

Compiler message:
note: this function takes ownership of the receiver self, which moves flight_path_segment

struct WayPoint<T> {
    name: String,
    latitude: T,
    longitude: T,

impl Segment {
    fn new(start: WayPoint<f64>, end: WayPoint<f64>) -> Self {
        Self {

    fn steal_ownership_fuction(self) -> String {
        "Test return".to_string()

struct Segment {
    start: WayPoint<f64>,
    end: WayPoint<f64>

fn main() {
    let way_point_fhl = WayPoint {
        name: "FHL".to_string(),
        latitude: 36.0036,
        longitude: -121.2313,

    let way_point_bonny_dune = WayPoint {
        name: "Bonny Dune".to_string(),
        latitude: 37.04167,
        longitude: -122.14944,

    //println!("{} {} {}",, test.longitude, test.latitude);

    let flight_path_segment = Segment::new(way_point_fhl, way_point_bonny_dune);

    // {:?} dump full object if it defines Debug
    println!("{:?}", flight_path_segment);

    println!("{}", flight_path_segment.steal_ownership_fuction());
    //Second call to same function breaks code
    println!("{}", flight_path_segment.steal_ownership_fuction());

The key is in the signature of steal_ownership_function:

fn steal_ownership_fuction(self) -> String { ... }

Notice the self. It means that the function takes ownership of the WayPoint you call it on (i.e., passes it by value), so that nothing else can use it again. Most of the time, this is not what you want. Instead, you can take self by reference, to borrow the receiver:

// if the function modifies `self`:
fn steal_ownership_fuction(&mut self) -> String { ... }
// if the function doesn't modify `self`:
fn steal_ownership_fuction(&self) -> String { ... }

Thank you!!! I just tried it with

    fn steal_ownership_fuction(&self) -> String {
        "Test return".to_string()

And it works perfectly. I have been doing python for too long :wink:


1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.