Why are 'new' and 'make' not reser

2019-08-12 04:59发布

问题:

With syntax highlighting enabled, it's distracting while reading code like answer to this question with new used as a variable name.

I'm trying to think of a reason why only a subset of keywords would be reserved and can't come up with a good one.

Edit: Alternate title for this question:

Why are Go's predeclared identifiers not reserved ?

回答1:

That's because new and make aren't really keywords, but built-in functions.

If you examine the full list of the reserved keywords, you won't see len or cap either...



回答2:

In short: because using predeclared identifiers in your own declarations don't make your code ambiguous.


new and make are builtin functions, amongst many others. See the full list in the doc of the builtin package.

Keywords are a carefully chosen small set of reserved words. You cannot use keywords as identifiers because that could make interpreting your source ambiguous.

Builtin functions are special functions: you can use them without any imports, and they may have varying parameter and return list. You are allowed to declare functions or variables with the names of the builtin functions because your code will still remain unambiguous: your identifier in scope will "win".

If you would use a keyword as an identifier, you couldn't reach your entity because an attempt to refer to it by its name would always mean the keyword and not your identifier.

See this dirty example of using the predeclared identifiers of the builtin function make and the builtin type int (not recommended for production code) (try it on the 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 declarations would cause headache to the compiler: what would the following mean?

  • func() - is it calling your function named func or is it a function type with no params and no return types?
  • import() - is it a grouped import declaration (and importing nothing) or calling our function named import?
  • ...