2022-09-08

Go for C# developers: Using keywords as identifiers

It doesn't happen very often but sometimes there is a variable name that makes sense that happens to be a reserved word in the language. In C# when this happens you prefix it with "@" so you get @new as a variable name. Not quite as clean with the prefix, but clear what is going on. Go takes a different approach.

It's a lesser known fact, but the number of reserved keywords in Go are actually not that many. Note how none of the built-in basic types or functions are actually reserved. Those are instead predeclared identifiers. The difference is that while reserved keywords can not be used as identifiers, all the predeclared identifiers can be used as identifiers. That is no different than when you declare a variable with a smaller scope when one is already used in the larger scope.

Reusing variable names in a smaller scope is mostly a bad idea since it is harder to spot bugs where you did not intend to actually use a smaller scope (example), it is very nifty when reusing a name, but having a newly scoped variable makes the code more clear.

Redefining predeclared identifiers in a smaller scope suffers from the same problem of potentially causing confusion, but especially the ability to use variable names as "new" and "copy" without having to worry about prefixing them can certainly make the code more clear.

That being said, there is almost always alternatives that are guaranteed to avoid confusion and I would recommend looking to those first. For example "n" is a pretty good replacement for "new" and "clone" is a pretty good replacement for "copy".

But...

If you're still looking to redefined the predeclared identifiers you can have a lot of fun and not only use them as variable names but also types and function names (these are all identifiers). If your code needs to handle string lights, this is some terrible inspiration on how to do that.

What if I like prefixing like in C#?

Well, the go specification does not let you prefix with "@", but just like in C# you can use unicode in your identifiers so if you really want to name a variable switch, I got some options for you.

Let me know what your colleagues think of your creative use of unicode and variable names!

No comments:

Post a Comment