Group Similar Declarations

Go supports grouping similar declarations.

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

This also applies to constants, variables, and type declarations.

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

Only group related declarations. Do not group declarations that are unrelated.

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

Groups are not limited in where they can be used. For example, you can use theminside of functions.

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