因素化的导入语句为什么更好?

huangapple go评论98阅读模式
英文:

Why is the factored import statement better?

问题

官方的Go语言教程中提到了一种类似于下面这样的分组导入的方式:

import (
    "fmt"
    "math"
)

然后,教程中有以下稍微不太清楚的备注:

> 你也可以写多个导入语句,像这样:
>
> import "fmt"
> import "math"
>
> 但是使用分组导入语句是一个好的风格。

实际上,使用其中一种方法是否有具体的优势,比如行为上的差异或者只有其中一种语法容易出现的拼写错误,还是这只是一种任意的风格约定?

英文:

The official tour of Go, after exhibiting a factored import like this...

import (
    "fmt"
    "math"
)

... contains the following slightly unclear remark:

> You can also write multiple import statements, like:
>
> import "fmt"
> import "math"
>
> But it is good style to use the factored import statement.

Is there actually any concrete advantage to using one approach over the other - such as a difference in behaviour or an easy-to-make typo that is only a danger with one of the two syntaxes - or is this just an arbitrary style convention?

答案1

得分: 20

除了需要输入的字符数量不同之外,没有其他区别。一个较大的程序或包可能会导入十几个或更多的包,所以为什么要一次又一次地输入相同的单词(import),当你可以用一对括号来实现相同的效果呢。

不过,现在大多数人可能都使用GoImports了。

英文:

There is no difference except for the amount of typing you have to do. A good sized program or package can easily have a dozen or more imported packages so why keep typing the same word (import) time and again when you can achieve the same with a pair of ().

Though most people probably use GoImports nowadays anyway.

答案2

得分: 7

对于Go编译器来说,这两种写法没有任何区别。区别只存在于Go程序员需要复制/输入import的次数上。你可以将其类比为以下两种写法:

func f1(n1, n2, n3 int){
    ...
}

vs

func f1(n1 int, n2 int, n3 int){
    ...
}

或者 var n1, n2, n3 int vs

var n1 int
var n2 int
var n3 int

两种写法都会产生相同的结果。

英文:

There is absolutely no difference for a go compiler. The difference is only for a go programmer in how many times he has to copy/type import. You can look at it in the same way as:

func f1(n1, n2, n3 int){
	...
}

vs

func f1(n1 int, n2 int, n3 int){
	...
}

or var n1, n2, n3 int vs

var n1 int
var n2 int
var n3 int

both will produce the same result.

huangapple
  • 本文由 发表于 2015年5月24日 23:03:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/30424935.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定