Understanding Exercise 40 note
alexbeloi opened this issue · comments
Alex Beloi commented
When I read this
// You can always make a const pointer to a mutable value (var), but
// you cannot make a var pointer to an immutable value (const).
// This sounds like a logic puzzle, but it just means that once data
// is declared immutable, you can't coerce it to a mutable type.
// Think of mutable data as being volatile or even dangerous. Zig
// always lets you be "more safe" and never "less safe."
I interpret it to mean that
const a: u8 = 1;
var x: *const u8 = &a; // Not ok?
but that works just fine.
On the other hand
const a: u8 = 1;
var b: u8 = 2;
const x: *const u8 = &a; // OK
const y: *const u8 = &b; // OK, mutable `b` coerced to const
var z: *u8 = &a; // NOT OK, const `a` cannot be coerced to mutable
var w: *u8 = &b; // OK
My confusion seems to be if the 'var' in 'var pointer' refer to the mutability of the pointer or the mutability type of it's pointing at. It seems like the correct interpretation is the latter, that 'var pointer' in the note is not var pointer
but rather one of const pointer: *T
or var pointer: *T
, and 'const pointer' is not const pointer
but rather one of const pointer: *const T
or var pointer: *const T
. Am I understanding that correctly?
P.S. It may be nice to start a Discussion board for these kind of topics.