@@ -21,6 +21,7 @@ mod filter_next;
21
21
mod flat_map_identity;
22
22
mod flat_map_option;
23
23
mod from_iter_instead_of_collect;
24
+ mod get_last_with_len;
24
25
mod get_unwrap;
25
26
mod implicit_clone;
26
27
mod inefficient_to_string;
@@ -1209,6 +1210,38 @@ declare_clippy_lint! {
1209
1210
"replace `.drain(..)` with `.into_iter()`"
1210
1211
}
1211
1212
1213
+ declare_clippy_lint ! {
1214
+ /// ### What it does
1215
+ /// Checks for using `x.get(x.len() - 1)` instead of
1216
+ /// `x.last()`.
1217
+ ///
1218
+ /// ### Why is this bad?
1219
+ /// Using `x.last()` is easier to read and has the same
1220
+ /// result.
1221
+ ///
1222
+ /// Note that using `x[x.len() - 1]` is semantically different from
1223
+ /// `x.last()`. Indexing into the array will panic on out-of-bounds
1224
+ /// accesses, while `x.get()` and `x.last()` will return `None`.
1225
+ ///
1226
+ /// There is another lint (get_unwrap) that covers the case of using
1227
+ /// `x.get(index).unwrap()` instead of `x[index]`.
1228
+ ///
1229
+ /// ### Example
1230
+ /// ```rust
1231
+ /// // Bad
1232
+ /// let x = vec![2, 3, 5];
1233
+ /// let last_element = x.get(x.len() - 1);
1234
+ ///
1235
+ /// // Good
1236
+ /// let x = vec![2, 3, 5];
1237
+ /// let last_element = x.last();
1238
+ /// ```
1239
+ #[ clippy:: version = "1.37.0" ]
1240
+ pub GET_LAST_WITH_LEN ,
1241
+ complexity,
1242
+ "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler"
1243
+ }
1244
+
1212
1245
declare_clippy_lint ! {
1213
1246
/// ### What it does
1214
1247
/// Checks for use of `.get().unwrap()` (or
@@ -2264,6 +2297,7 @@ impl_lint_pass!(Methods => [
2264
2297
BYTES_NTH ,
2265
2298
ITER_SKIP_NEXT ,
2266
2299
GET_UNWRAP ,
2300
+ GET_LAST_WITH_LEN ,
2267
2301
STRING_EXTEND_CHARS ,
2268
2302
ITER_CLONED_COLLECT ,
2269
2303
ITER_WITH_DRAIN ,
@@ -2590,6 +2624,7 @@ impl Methods {
2590
2624
inspect_for_each:: check ( cx, expr, span2) ;
2591
2625
}
2592
2626
} ,
2627
+ ( "get" , [ arg] ) => get_last_with_len:: check ( cx, expr, recv, arg) ,
2593
2628
( "get_or_insert_with" , [ arg] ) => unnecessary_lazy_eval:: check ( cx, expr, recv, arg, "get_or_insert" ) ,
2594
2629
( "is_file" , [ ] ) => filetype_is_file:: check ( cx, expr, recv) ,
2595
2630
( "is_digit" , [ radix] ) => is_digit_ascii_radix:: check ( cx, expr, recv, radix, self . msrv ) ,
0 commit comments