Avoiding compiler suggestion to clone value

This triggers the compiler to suggest cloning data before passing it to a function:

    // v1: from get() in hashmap
    let data_type = match args.entries.get("data") {
        Some(value) => value,
        None => panic!("Error (none): args.entries.data."),
     };
    let data = match data_type {
        ArgsType::Data(value) => value,
    };

This does not:

   // v2: from get_data() in struct implementation
    let data = match args.get_data() {
        Some(value) => value,
        None => panic!("Error (none): args.data."),
    };

Error:

  --> src/model/mod.rs:35:45
   |
35 |     let data = my_func(data);
   |                           ----------------- ^^^^^^^^^ expected `Data`, found `&Data`
   |                           |
   |                           arguments to this method are incorrect
   |
note: method defined here
  --> src/model/types/model/mod.rs:71:12
   |
71 |     pub fn my_func(&mut self, mut data: Data) -> Data {
   |            ^^^^^^^^^^^^^^^^^            -----------------------
help: consider using clone here
   |
35 |     let data = my_func(data.clone());
  • Why?
  • Can I avoid the extra clone somehow?
  • How did I end up with &Data instead of Data when I didn't specify & in line 35?

Figured it out while writing the post.

  • In v2, the method get_data() returns a clone. It was already necessary - I just didn't remember. Adding a .clone() to the second match statement in v1 clears the error.
    ArgsType::Data(value) => value.clone().

But I still don't know how I ended up with &Data instead of Data when I didn't specify & in line 35.

Presumably args.entries is a HashMap<_, Data>. HashMap::get returns Option<&V>.

Ah. OK. That makes sense. I wouldn't have guessed that from the error message, but I guess the point is that I need to recursively check return-types for all the objects when I get these type-mismatch errors.

When using an editor/IDE with rust-analyzer, what I do is look at the type of the data variable to confirm it is a ref. That at least tells me the compiler error is not misleading.

Never used rust-analyzer. Looking at the docs, that could be a nice side-quest. Thanks for the mention.

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.