Convert by as

Rust provides no implicit type conversion(coercion) between primitive types. But explicit type conversions can be performed using the as keyword.

  1. 🌟
1. // FIX the errors and FILL in the blank
2. // DON'T remove any code
3. fn main() {
4. let decimal = 97.123_f32;

6. let integer: __ = decimal as u8;

8. let c1: char = decimal as char;
9. let c2 = integer as char;

11. assert_eq!(integer, 'b' as u8);

13. println!("Success!");
14. }
  1. 🌟🌟 By default, overflow will cause compile errors, but we can add an global annotation to suppress these errors.
1. fn main() {
2. assert_eq!(u8::MAX, 255);
3. // The max of `u8` is 255 as shown above.
4. // so the below code will cause an overflow error: literal out of range for `u8`.
5. // PLEASE looking for clues within compile errors to FIX it.
6. // DON'T modify any code in main.
7. let v = 1000 as u8;

9. println!("Success!");
10. }
  1. 🌟🌟 When casting any value to an unsigned type T, T::MAX + 1 is added or subtracted until the value fits into the new type.
1. fn main() {
2. assert_eq!(1000 as u16, __);

4. assert_eq!(1000 as u8, __);

6. // For positive numbers, this is the same as the modulus
7. println!("1000 mod 256 is : {}", 1000 % 256);

9. assert_eq!(-1_i8 as u8, __);

11. // Since Rust 1.45, the `as` keyword performs a *saturating cast*
12. // when casting from float to int. If the floating point value exceeds
13. // the upper bound or is less than the lower bound, the returned value
14. // will be equal to the bound crossed.
15. assert_eq!(300.1_f32 as u8, __);
16. assert_eq!(-100.1_f32 as u8, __);

18. // This behavior incurs a small runtime cost and can be avoided
19. // with unsafe methods, however the results might overflow and
20. // return **unsound values**. Use these methods wisely:
21. unsafe {
22. // 300.0 is 44
23. println!("300.0 is {}", 300.0_f32.to_int_unchecked::<u8>());
24. // -100.0 as u8 is 156
25. println!("-100.0 as u8 is {}", (-100.0_f32).to_int_unchecked::<u8>());
26. // nan as u8 is 0
27. println!("nan as u8 is {}", f32::NAN.to_int_unchecked::<u8>());
28. }
29. }
  1. 🌟🌟🌟 Raw pointers can be converted to memory address (integer) and vice versa.
2. // FILL in the blanks
3. fn main() {
4. let mut values: [i32; 2] = [1, 2];
5. let p1: *mut i32 = values.as_mut_ptr();
6. let first_address: usize = p1 __;
7. let second_address = first_address + 4; // 4 == std::mem::size_of::<i32>()
8. let p2: *mut i32 = second_address __; // p2 points to the 2nd element in values
9. unsafe {
10. // Add one to the second element
11. __
12. }

14. assert_eq!(values[1], 3);

16. println!("Success!");
17. }
  1. 🌟🌟🌟
1. fn main() {
2. let arr :[u64; 13] = [0; 13];
3. assert_eq!(std::mem::size_of_val(&arr), 8 * 13);
4. let a: *const [u64] = &arr;
5. let b = a as *const [u8];
6. unsafe {
7. assert_eq!(std::mem::size_of_val(&*b), __)
8. }

10. println!("Success!");
11. }

You can find the solutions here(under the solutions path), but only use it when you need it