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