4 ms·
No, they are very different conceptually. - A const is an abstracted value. - A variable is an allocated piece of memory.
by JulianMorrison 5y ago
No, they are very different conceptually.
- A const is an abstracted value.
- A variable is an allocated piece of memory.
- tapirl 5y agoConcepts are defined as needed.
- JulianMorrison 5y agoThat wasn't exactly what I meant. What I meant was - as of right now they are different, and clearly distinct, and it's actually important to unlearn thinking of a const as a var, because they don't do the same thing in practical terms - that proposal would muddy the distinction.
- tapirl 5y agoYes, they are different, const values doesn't allocated in memory NOW. But who cares? Most gophers just think const values are immutable values. I mean we could let some const values allocated in memory.
- JulianMorrison 5y agoThankfully the people who make Go do care about conceptual muddles.
- mikepurvis 5y agoIsn't that an implementation choice? Like in C++, a const is absolutely allocated since you can get a pointer to one. And then you can do horrible stuff like const_cast that pointer and mutate the value, and the possibility of that occurring prevents the compiler from doing certain const-related optimizations.
- JulianMorrison 5y agoYes, it is an implementation choice. I feel it's a choice that makes sense, too. But regardless, it's how things work right now in Go.
- catlifeonmars 5y ago> Like in C++, a const is absolutely allocated since you can get a pointer to one. If I understand you correctly, you claim you can get a pointer to a Go const. This is not the case. For example, the following code will not compile: const a int = 1 var b *int = &a ./prog.go:5:15: cannot take the address of a See https://go.dev/play/p/QPxP-tF6qIs https://go.dev/play/p/QPxP-tF6qIs for a live example.
- mikepurvis 5y agoI'm not an active golang user, so it wasn't a comment on that, more just on the GP's assertion that a const had to be an abstracted value. It sounds like that is indeed the case in Go (an implementation choice), but more broadly, I wouldn't expect "const" to mean anything more to most programmers than "give me an error if I or anyone else try to modify this thing." And in C++, it certainly isn't. Even a constexpr in C++ is a thing you can get a pointer-to— C++'s only guarantee with a constexpr is that it has to be possible to evaluate it at compile time.
- catlifeonmars 5y agoAh gotcha. Makes sense. The way I typically think of Go const is more akin to a typed macro, rather than a first class value reference where it is expanded in place. Notably, in Go constants cannot contain structs, arrays, so they have much less to do with mutability than in, say, in C++.