]> git.lizzy.rs Git - rust.git/blob - src/docs/pattern_type_mismatch.txt
new uninlined_format_args lint to inline explicit arguments
[rust.git] / src / docs / pattern_type_mismatch.txt
1 ### What it does
2 Checks for patterns that aren't exact representations of the types
3 they are applied to.
4
5 To satisfy this lint, you will have to adjust either the expression that is matched
6 against or the pattern itself, as well as the bindings that are introduced by the
7 adjusted patterns. For matching you will have to either dereference the expression
8 with the `*` operator, or amend the patterns to explicitly match against `&<pattern>`
9 or `&mut <pattern>` depending on the reference mutability. For the bindings you need
10 to use the inverse. You can leave them as plain bindings if you wish for the value
11 to be copied, but you must use `ref mut <variable>` or `ref <variable>` to construct
12 a reference into the matched structure.
13
14 If you are looking for a way to learn about ownership semantics in more detail, it
15 is recommended to look at IDE options available to you to highlight types, lifetimes
16 and reference semantics in your code. The available tooling would expose these things
17 in a general way even outside of the various pattern matching mechanics. Of course
18 this lint can still be used to highlight areas of interest and ensure a good understanding
19 of ownership semantics.
20
21 ### Why is this bad?
22 It isn't bad in general. But in some contexts it can be desirable
23 because it increases ownership hints in the code, and will guard against some changes
24 in ownership.
25
26 ### Example
27 This example shows the basic adjustments necessary to satisfy the lint. Note how
28 the matched expression is explicitly dereferenced with `*` and the `inner` variable
29 is bound to a shared borrow via `ref inner`.
30
31 ```
32 // Bad
33 let value = &Some(Box::new(23));
34 match value {
35     Some(inner) => println!("{}", inner),
36     None => println!("none"),
37 }
38
39 // Good
40 let value = &Some(Box::new(23));
41 match *value {
42     Some(ref inner) => println!("{}", inner),
43     None => println!("none"),
44 }
45 ```
46
47 The following example demonstrates one of the advantages of the more verbose style.
48 Note how the second version uses `ref mut a` to explicitly declare `a` a shared mutable
49 borrow, while `b` is simply taken by value. This ensures that the loop body cannot
50 accidentally modify the wrong part of the structure.
51
52 ```
53 // Bad
54 let mut values = vec![(2, 3), (3, 4)];
55 for (a, b) in &mut values {
56     *a += *b;
57 }
58
59 // Good
60 let mut values = vec![(2, 3), (3, 4)];
61 for &mut (ref mut a, b) in &mut values {
62     *a += b;
63 }
64 ```