• 声明分组

    声明分组

    Go 支持将相似的声明分组:

    BadGood
    1. import "a"
    2. import "b"
    1. import (
    2. "a"
    3. "b"
    4. )

    分组同样适用于常量、变量和类型的声明:

    BadGood
    1. const a = 1
    2. const b = 2
    3. var a = 1
    4. var b = 2
    5. type Area float64
    6. type Volume float64
    1. const (
    2. a = 1
    3. b = 2
    4. )
    5. var (
    6. a = 1
    7. b = 2
    8. )
    9. type (
    10. Area float64
    11. Volume float64
    12. )

    仅将相似的声明放在同一组。不相关的声明不要放在同一个组内。

    BadGood
    1. type Operation int
    2. const (
    3. Add Operation = iota + 1
    4. Subtract
    5. Multiply
    6. ENV_VAR = "MY_ENV"
    7. )
    1. type Operation int
    2. const (
    3. Add Operation = iota + 1
    4. Subtract
    5. Multiply
    6. )
    7. const ENV_VAR = "MY_ENV"

    声明分组可以在任意位置使用。例如,可以在函数内部使用。

    BadGood
    1. func f() string {
    2. var red = color.New(0xff0000)
    3. var green = color.New(0x00ff00)
    4. var blue = color.New(0x0000ff)
    5. }
    1. func f() string {
    2. var (
    3. red = color.New(0xff0000)
    4. green = color.New(0x00ff00)
    5. blue = color.New(0x0000ff)
    6. )
    7. }