Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Understanding Exercise 40 note #364

Closed
alexbeloi opened this issue Nov 15, 2023 · 0 comments
Closed

Understanding Exercise 40 note #364

alexbeloi opened this issue Nov 15, 2023 · 0 comments

Comments

@alexbeloi
Copy link

alexbeloi commented Nov 15, 2023

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.

@alexbeloi alexbeloi closed this as not planned Won't fix, can't repro, duplicate, stale Nov 27, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant