3

I don't understand why Rust moves the value. Do I oversee a major point in the ownership?

The struct MyData is a smaller version. I store some values in this struct, and want to access the stored values, but the compiler tells me after the second access, that the value was moved.

I want to make some getters for my structs. I already derived Clone, but that does not help.

The problem occurs on Windows 10 with the GNU-Compiler and on Kubuntu 18.04 LTS.

My current workaround is to clone the data beforehand, but this can't be the correct way.

#[derive(Debug, Clone)]
struct MyData {
    val1: i32,
    val2: String,
}

impl MyData {
    pub fn get_val1(self) -> i32 {
        return self.val1.clone();
    }

    pub fn get_val2(self) -> String {
        return self.val2.clone();
    }

    pub fn get_both(self) -> (i32, String) {
        return (self.val1, self.val2);
    }
}

fn main() {
    let d = MyData {
        val1: 35,
        val2: String::from("Hello World"),
    };

    let both = d.get_both();
    let x = d.get_val1();
    let y = d.get_val2();
}
error[E0382]: use of moved value: `d`
  --> src/main.rs:28:13
   |
27 |     let both = d.get_both();
   |                - value moved here
28 |     let x = d.get_val1();
   |             ^ value used here after move
   |
   = note: move occurs because `d` has type `MyData`, which does not implement the `Copy` trait

error[E0382]: use of moved value: `d`
  --> src/main.rs:29:13
   |
28 |     let x = d.get_val1();
   |             - value moved here
29 |     let y = d.get_val2();
   |             ^ value used here after move
   |
   = note: move occurs because `d` has type `MyData`, which does not implement the `Copy` trait

I expect that let x = d.get_val1(); won't cause an error. In my understanding of ownership in Rust, I did not move the value, since I'm calling a method of MyData and want to work with the value.

Why does Rust move the value and to whom?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
tarantel
  • 64
  • 4
  • Please take some time to read [*The Rust Programming Language*](https://doc.rust-lang.org/book/), which has [multiple chapters about ownership](https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html). Ownership is a fundamental concept in Rust and not taking the time to properly learn it will cause great heartache. – Shepmaster Apr 07 '19 at 15:38
  • 5
    TL;DR — [use `&self` instead of `self` in your methods](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=ac1630aee7194d3e02afeea229c78465). Note that an explicit `return` is not idiomatic Rust. – Shepmaster Apr 07 '19 at 15:40
  • Thank you very much! Then I will dive again into the chapters about ownershipt. It's a habit from other programming languages to write `return`. It's hard to omit it at the moment. – tarantel Apr 07 '19 at 15:42

0 Answers0