From: LukeMathWalker <20745048+LukeMathWalker@users.noreply.github.com> Date: Thu, 23 May 2024 12:37:05 +0000 (+0200) Subject: Improve `as` casting exercise. X-Git-Url: http://git.euphorik.ch/?a=commitdiff_plain;h=f645b500c43e714c9b6f880c27a5b286e33328b0;p=rust_exercises.git Improve `as` casting exercise. --- diff --git a/exercises/02_basic_calculator/10_as_casting/src/lib.rs b/exercises/02_basic_calculator/10_as_casting/src/lib.rs index 7b8b3e0..b1921d0 100644 --- a/exercises/02_basic_calculator/10_as_casting/src/lib.rs +++ b/exercises/02_basic_calculator/10_as_casting/src/lib.rs @@ -6,17 +6,32 @@ mod tests { #[test] fn u16_to_u32() { - assert_eq!(47u16 as u32, todo!()); + let v: u32 = todo!(); + assert_eq!(47u16 as u32, v); } #[test] - #[allow(overflowing_literals)] fn u8_to_i8() { - assert_eq!(255 as i8, todo!()); + // The compiler is smart enough to know that the value 255 cannot fit + // inside an i8, so it'll emit a hard error. We intentionally disable + // this guardrail to make this (bad) conversion possible. + // The compiler is only able to pick on this because the value is a + // literal. If we were to use a variable, the compiler wouldn't be able to + // catch this at compile time. + #[allow(overflowing_literals)] + let x = { 255 as i8 }; + + // You could solve this by using exactly the same expression as above, + // but that would defeat the purpose of the exercise. Instead, use a genuine + // `i8` value that is equivalent to `255` when converted from `u8`. + let y: i8 = todo!(); + + assert_eq!(x, y); } #[test] fn bool_to_u8() { - assert_eq!(true as u8, todo!()); + let v: u8 = todo!(); + assert_eq!(true as u8, v); } }