summaryrefslogtreecommitdiff
path: root/solutions/22_clippy
diff options
context:
space:
mode:
authormo8it <mo8it@proton.me>2024-07-05 13:39:50 +0200
committermo8it <mo8it@proton.me>2024-07-05 13:39:50 +0200
commit7123c7ae3a9605fbe962e4ef0a0f1424cd16fef8 (patch)
treec67f7e62bb9a179ae4fdbab492501cb6847e64c7 /solutions/22_clippy
parent77b687d501771c24bd83294d97b8e6f9ffa92d6b (diff)
parent4d9c346a173bb722b929f3ea3c00f84954483e24 (diff)
Merge remote-tracking branch 'upstream/main' into fix-enum-variant-inconsistency
Diffstat (limited to 'solutions/22_clippy')
-rw-r--r--solutions/22_clippy/clippy1.rs17
-rw-r--r--solutions/22_clippy/clippy2.rs10
-rw-r--r--solutions/22_clippy/clippy3.rs31
3 files changed, 58 insertions, 0 deletions
diff --git a/solutions/22_clippy/clippy1.rs b/solutions/22_clippy/clippy1.rs
new file mode 100644
index 0000000..b9d1ec1
--- /dev/null
+++ b/solutions/22_clippy/clippy1.rs
@@ -0,0 +1,17 @@
+// The Clippy tool is a collection of lints to analyze your code so you can
+// catch common mistakes and improve your Rust code.
+//
+// For these exercises, the code will fail to compile when there are Clippy
+// warnings. Check Clippy's suggestions from the output to solve the exercise.
+
+use std::f32::consts::PI;
+
+fn main() {
+ // Use the more accurate `PI` constant.
+ let pi = PI;
+ let radius: f32 = 5.0;
+
+ let area = pi * radius.powi(2);
+
+ println!("The area of a circle with radius {radius:.2} is {area:.5}");
+}
diff --git a/solutions/22_clippy/clippy2.rs b/solutions/22_clippy/clippy2.rs
new file mode 100644
index 0000000..7f63562
--- /dev/null
+++ b/solutions/22_clippy/clippy2.rs
@@ -0,0 +1,10 @@
+fn main() {
+ let mut res = 42;
+ let option = Some(12);
+ // Use `if-let` instead of iteration.
+ if let Some(x) = option {
+ res += x;
+ }
+
+ println!("{res}");
+}
diff --git a/solutions/22_clippy/clippy3.rs b/solutions/22_clippy/clippy3.rs
new file mode 100644
index 0000000..811d184
--- /dev/null
+++ b/solutions/22_clippy/clippy3.rs
@@ -0,0 +1,31 @@
+use std::mem;
+
+#[rustfmt::skip]
+#[allow(unused_variables, unused_assignments)]
+fn main() {
+ let my_option: Option<()> = None;
+ // `unwrap` of an `Option` after checking if it is `None` will panic.
+ // Use `if-let` instead.
+ if let Some(value) = my_option {
+ println!("{value:?}");
+ }
+
+ // A comma was missing.
+ let my_arr = &[
+ -1, -2, -3,
+ -4, -5, -6,
+ ];
+ println!("My array! Here it is: {:?}", my_arr);
+
+ let mut my_empty_vec = vec![1, 2, 3, 4, 5];
+ // `resize` mutates a vector instead of returning a new one.
+ // `resize(0, …)` clears a vector, so it is better to use `clear`.
+ my_empty_vec.clear();
+ println!("This Vec is empty, see? {my_empty_vec:?}");
+
+ let mut value_a = 45;
+ let mut value_b = 66;
+ // Use `mem::swap` to correctly swap two values.
+ mem::swap(&mut value_a, &mut value_b);
+ println!("value a: {}; value b: {}", value_a, value_b);
+}