040_pointers2.zig 802 B

1234567891011121314151617181920212223242526272829
  1. //
  2. // It's important to note that variable pointers and constant pointers
  3. // are different types.
  4. //
  5. // Given:
  6. //
  7. // var foo: u8 = 5;
  8. // const bar: u8 = 5;
  9. //
  10. // Then:
  11. //
  12. // &foo is of type "*u8"
  13. // &bar is of type "*const u8"
  14. //
  15. // You can always make a const pointer to a mutable value (var), but
  16. // you cannot make a var pointer to an immutable value (const).
  17. // This sounds like a logic puzzle, but it just means that once data
  18. // is declared immutable, you can't coerce it to a mutable type.
  19. // Think of mutable data as being volatile or even dangerous. Zig
  20. // always lets you be "more safe" and never "less safe."
  21. //
  22. const std = @import("std");
  23. pub fn main() void {
  24. const a: u8 = 12;
  25. const b: *u8 = &a; // fix this!
  26. std.debug.print("a: {}, b: {}\n", .{ a, b.* });
  27. }