四. 样式
相似的声明放在一组
Go语言支持将相似的声明放在一个组内:
Bad
import “a”
import “b”
vs.
Good
import (
“a”
“b”
)
这同样适用于常量、变量和类型声明:
Bad
const a = 1
const b = 2
var a = 1
var b = 2
type Area float64
type Volume float64
vs.
Good
const (
a = 1
b = 2
)
var (
a = 1
b = 2
)
type (
Area float64
Volume float64
)
仅将相关的声明放在一组。不要将不相关的声明放在一组。
Bad
type Operation int
const (
Add Operation = iota + 1
Subtract
Multiply
ENV_VAR = “MY_ENV”
)
vs.
Good
type Operation int
const (
Add Operation = iota + 1
Subtract
Multiply
)
const ENV_VAR = “MY_ENV”
分组使用的位置没有限制,例如:你可以在函数内部使用它们:
Bad
func f() string {
var red = color.New(0xff0000)
var green = color.New(0x00ff00)
var blue = color.New(0x0000ff)
…
}
vs.
Good
func f() string {
var (
red = color.New(0xff0000)
green = color.New(0x00ff00)
blue = color.New(0x0000ff)
)
…
}