061_coercions.zig 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. //
  2. // It'll only take us a moment to learn the Zig type coercion
  3. // rules because they're quite logical.
  4. //
  5. // 1. Types can always be made _more_ restrictive.
  6. //
  7. // var foo: u8 = 5;
  8. // var p1: *u8 = &foo;
  9. // var p2: *const u8 = p1; // mutable to immutable
  10. //
  11. // 2. Numeric types can coerce to _larger_ types.
  12. //
  13. // var n1: u8 = 5;
  14. // var n2: u16 = n1; // integer "widening"
  15. //
  16. // var n3: f16 = 42.0;
  17. // var n4: f32 = n3; // float "widening"
  18. //
  19. // 3. Single-item pointers to arrays coerce to slices and
  20. // many-item pointers.
  21. //
  22. // const arr: [3]u8 = [3]u8{5, 6, 7};
  23. // const s: []const u8 = &arr; // to slice
  24. // const p: [*]const u8 = &arr; // to many-item pointer
  25. //
  26. // 4. Single-item mutable pointers can coerce to single-item
  27. // pointers pointing to an array of length 1. (Interesting!)
  28. //
  29. // var five: u8 = 5;
  30. // var a_five: *[1]u8 = &five;
  31. //
  32. // 5. Payload types and null coerce to optionals.
  33. //
  34. // var num: u8 = 5;
  35. // var maybe_num: ?u8 = num; // payload type
  36. // maybe_num = null; // null
  37. //
  38. // 6. Payload types and errors coerce to error unions.
  39. //
  40. // const MyError = error{Argh};
  41. // var char: u8 = 'x';
  42. // var char_or_die: MyError!u8 = char; // payload type
  43. // char_or_die = MyError.Argh; // error
  44. //
  45. // 7. 'undefined' coerces to any type (or it wouldn't work!)
  46. //
  47. // 8. Compile-time numbers coerce to compatible types.
  48. //
  49. // Just about every single exercise program has had an example
  50. // of this, but a full and proper explanation is coming your
  51. // way soon in the third-eye-opening subject of comptime.
  52. //
  53. // 9. Tagged unions coerce to the current tagged enum.
  54. //
  55. // 10. Enums coerce to a tagged union when that tagged field is a
  56. // a zero-length type that has only one value (like void).
  57. //
  58. // 11. Zero-bit types (like void) can be coerced into single-item
  59. // pointers.
  60. //
  61. // The last three are fairly esoteric, but you're more than
  62. // welcome to read more about them in the official Zig language
  63. // documentation and write your own experiments.
  64. const print = @import("std").debug.print;
  65. pub fn main() void {
  66. var letter: u8 = 'A';
  67. const my_letter: ??? = &letter;
  68. // ^^^^^^^
  69. // Your type here.
  70. // Must coerce from &letter (which is a *u8).
  71. // Hint: Use coercion Rules 4 and 5.
  72. // When it's right, this will work:
  73. print("Letter: {u}\n", .{my_letter.?.*[0]});
  74. }