Improve `as` casting exercise.
This commit is contained in:
parent
bf1cdfdb5c
commit
f645b500c4
|
@ -6,17 +6,32 @@ mod tests {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn u16_to_u32() {
|
fn u16_to_u32() {
|
||||||
assert_eq!(47u16 as u32, todo!());
|
let v: u32 = todo!();
|
||||||
|
assert_eq!(47u16 as u32, v);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[allow(overflowing_literals)]
|
|
||||||
fn u8_to_i8() {
|
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]
|
#[test]
|
||||||
fn bool_to_u8() {
|
fn bool_to_u8() {
|
||||||
assert_eq!(true as u8, todo!());
|
let v: u8 = todo!();
|
||||||
|
assert_eq!(true as u8, v);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue