Why are “new” and “made” keywords not reserved?

With syntax highlighting turned on, this distracts when reading the code, for example, the answer to this question , with a new name used as the name of the variable.

I am trying to come up with a reason why only a subset of the keywords will be reserved and cannot come up with a good one.

Edit: Alternative name for this question:

Why are invalid Go identifiers invalid?

+1
source share
2 answers

This is because new and make are not keywords, but built-in functions.

If you look at the full list of reserved keywords you won’t see len or cap either ...

+3
source

In short: because using predefined identifiers in your own ads does not make your code ambiguous.


new and make are built-in functions, among many others. See the complete list in the builtin document.

Keywords is a carefully selected small set of reserved words. You cannot use keywords as identifiers, because this can make the interpretation of your source ambiguous.

Built-in functions are special functions: you can use them without any imports, and they can have various parameters and a return list. You are allowed to declare functions or variables with the names of the built-in functions, because your code will still remain unambiguous: your identifier in the field will “win”.

If you used the keyword as an identifier, you would not be able to reach your object, because trying to refer to it by its name will always mean the keyword, not your identifier.

See this dirty example of using the predefined identifiers of the built-in function make and the built-in type int (not recommended for production code) (try on Go Playground ):

 make := func() string { return "hijacked" } int := make() // Completely OK, variable 'int' will be a string fmt.Println(int) // Prints "hijacked" 

If you could use keywords as identifiers, even interpreting the declarations could cause a headache for the compiler: what would this mean:

  • func() a call to your function named func or is it a function type without parameters and return types?
  • Is import() a grouped import declaration (and import nothing) or a call to our function named import ?
  • ...
+2
source

Source: https://habr.com/ru/post/1245613/


All Articles