@@ -21,6 +21,7 @@ mod filter_next;
2121mod flat_map_identity;
2222mod flat_map_option;
2323mod from_iter_instead_of_collect;
24+ mod get_last_with_len;
2425mod get_unwrap;
2526mod implicit_clone;
2627mod inefficient_to_string;
@@ -1209,6 +1210,38 @@ declare_clippy_lint! {
12091210 "replace `.drain(..)` with `.into_iter()`"
12101211}
12111212
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+
12121245declare_clippy_lint ! {
12131246 /// ### What it does
12141247 /// Checks for use of `.get().unwrap()` (or
@@ -2264,6 +2297,7 @@ impl_lint_pass!(Methods => [
22642297 BYTES_NTH ,
22652298 ITER_SKIP_NEXT ,
22662299 GET_UNWRAP ,
2300+ GET_LAST_WITH_LEN ,
22672301 STRING_EXTEND_CHARS ,
22682302 ITER_CLONED_COLLECT ,
22692303 ITER_WITH_DRAIN ,
@@ -2590,6 +2624,7 @@ impl Methods {
25902624 inspect_for_each:: check ( cx, expr, span2) ;
25912625 }
25922626 } ,
2627+ ( "get" , [ arg] ) => get_last_with_len:: check ( cx, expr, recv, arg) ,
25932628 ( "get_or_insert_with" , [ arg] ) => unnecessary_lazy_eval:: check ( cx, expr, recv, arg, "get_or_insert" ) ,
25942629 ( "is_file" , [ ] ) => filetype_is_file:: check ( cx, expr, recv) ,
25952630 ( "is_digit" , [ radix] ) => is_digit_ascii_radix:: check ( cx, expr, recv, radix, self . msrv ) ,
0 commit comments