I was rather surprised that io.EOF
is not declared a constant, but an exported variable. Although not a big deal, this subjects it to unintended reassignment. Why not declare it a constant? Is this because constants in Go are rather unusual?
Asked
Active
Viewed 412 times
0

Kedar Mhaswade
- 4,535
- 2
- 25
- 34
-
1The decision was that predeclared errors should be singletons, so that comparing different instances of errors would not be unexpectedly equal. – JimB Jan 26 '19 at 19:25
-
SO is weird. I can't correct my previous comment (since, apparently, it is more than 2 hours old -- deleting that comment is not an option). Here's the [correct link](https://dave.cheney.net/2016/04/07/constant-errors) demonstrating that others make this observation too (`Could we change the definition of io.EOF to be a constant?`), @Flimzy. – Kedar Mhaswade Jan 26 '19 at 21:12
-
That's because then you'll have to delete your comment which would otherwise be rendered _dangling_ (you should delete your comment and then I can delete my first comment). By the way, do you know the answer to my question? – Kedar Mhaswade Jan 26 '19 at 22:43
-
Also this answer gives some insight: [Custom errors in golang and pointer receivers](https://stackoverflow.com/questions/50333428/custom-errors-in-golang-and-pointer-receivers/50333850#50333850) (constants can't be pointers). – icza Jan 27 '19 at 08:34
-
Dangling comments are not really a concern. Comments are always considered ephemeral. – Jonathan Hall Jan 27 '19 at 12:36
-
1I'm still not sure why you say constants are "unusual". Are you referring to the way Go handles untyped constants? – Jonathan Hall Jan 27 '19 at 12:37
-
@icza thanks! From [the Go Blog](https://blog.golang.org/constants): "But in Go, a constant is just a simple, unchanging value, and from here on we're talking only about Go." -- My question: is it _not_ possible to have this restriction (unchanging value) and still make `io.EOF` a constant (because it _feels_ and _behaves_ like one)? – Kedar Mhaswade Jan 27 '19 at 14:10
-
Of course it’s possible, but the language wasn’t designed that way. What real world benefit would this have for the added complication to the spec and implementation? Users can always write bad code and do bad things; someone reassigning `io.EOF` just isn’t considered a significant issue. – JimB Jan 27 '19 at 14:18
-
@JimB, thanks. I agree, this question perhaps solicits answers from the language designers. The [link](https://dave.cheney.net/2016/04/07/constant-errors) provides some ideas about implementation without changing the spec at all. The pivotal question is: Should a _value_ of a type other than basic types be allowed to be a constant? – Kedar Mhaswade Jan 27 '19 at 14:38
-
The example in that post demonstrates why they chose to implement `errors.New` the way they did, specifically so that different instances don’t compare as equal. – JimB Jan 27 '19 at 14:43