Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does _ mean in type errors in Rust?

Tags:

rust

I received this error:

error: mismatched types [E0308]
                         process(s);
                                 ^
help: run `rustc --explain E0308` to see a detailed explanation
note: expected type `&(u32, u32, image::Luma<u8>)`
note:    found type `&mut (u32, u32, &mut _)`

but I do not understand what the _ means.

like image 454
Kamil Szot Avatar asked Jan 06 '23 20:01

Kamil Szot


2 Answers

In Rust, the _ identifier is used when the name does not matter. This occurs in a few situations:

  • let _ = ...; is used to ignore the result of an expression (only necessary when said result is marked with the #[must_use] attribute)
  • In types, _ is used to elide types (either because you prefer to let the compiler infer it or because the compiler judges it does not matter)

Thus, in your case, the compiler has elided the type because it does not matter, so that you can focus on the specific reason of the error. It may be confusing, at first, but once used to it it's actually helpful, especially when types are hairy (very large).


The error is simple: you are mistaking references and values.

Your original signature expects: &(u32, u32, Type) but you pass &mut (u32, u32, &mut Type).

The difference in mutability does not matter (in this direction), however a &mut Type and a Type have very different memory structure and are not interchangeable.

like image 110
Matthieu M. Avatar answered Jan 16 '23 10:01

Matthieu M.


The _ is just a placeholder that could mean anything, and helps to clarify the error message.

In this case, it's saying it was expecting an image::Luma<u8>, but it actually found a mutable reference (&mut) to something. It doesn't matter what that something is; it &mut <something> can never be matched with image::Luma<i>.

If instead it said ...found type &mut (u32, u32, &mut T: SomeTrait) or similar, I think it would be harder to zoom in to the immediate problem.

You can't pass a reference to a function that expects an copied (or moved) full object instead.

like image 30
Chris Emerson Avatar answered Jan 16 '23 09:01

Chris Emerson