Is the Go “import” syntax special and unique?

2019-08-14 04:49发布

问题:

http://golang.org/ref/spec#Import_declarations

import "package1"

import ("package1";"package2")

import (
        "package1"
        "package2"
       )

Is the "import" syntax something especially made for importing packages? It looks like a function call that uses ";" instead of "," for parameterization. It seems that it could even have been a ruby-esque method call (ie: sans "()")

PS Thought I'd ask this to get some perspective. I'm really enjoying working with Go, but some of its syntax seems a bit inconsistent and sometimes verbose. Makes me wonder how hard it would be to create a pre-processor for it like C++ is/was to C to clean up some of the syntax. Call it Go++ (go faster). I'm thinking of Objective C 2.0 as a great example to improving the programmer's workflow (eg: dictionary/array/number literals). Go++ would also be similar in concept to exlixir-lang.org (a syntactical enhancement on top of Erlang).

回答1:

Yes import is special. It's required to be at the top of the file and it's arguments are always literals. This has to happen because go does a lot with trying to manage dependencies to speed up build times.

It also can't just be a regular environment because it injects variables into the current scope, something no other function can do.

As for the syntax, yeah some parts are not exactly pleasant. But it's a pretty minor concern to me and most other people who write Go that I've encountered. On the upside, the syntax is dead simple to parse so tooling is relatively straightforward which is why I worry about just changing the syntax for a few keystrokes.