Variables in Go

Go: Variables

In Go, variables are explicitly declared and used by the compiler.

  1. var can declares one or more variables, you can declare multiple variables at once.
    var a = "initial"
    fmt.Println(a)
    var b, c int = 1, 2
    fmt.Println(b, c)
  1. Go will infer the type of initialized variables.
    var d = true
    fmt.Println(d)
  1. Variables declared without a corresponding initialization are zero-valued. For example, the zero value for an int is 0.
    var e int
    fmt.Println(e)
  1. := syntax - is shorthand for declaring and initializing a variable.
    f := "20"

While declaring variable in Golang below naming convention should be followed -

  • A variable or constant name can only start with a letter or an underscore.
  • It can be followed by any number of letters, numbers or underscores after that
  • Go is case sensitive so uppercase and lowercase letters are treated differently.
  • The variable or constant name cannot be any keyword name in Go
  • There is no limit on the length of variable or constant name. But is advisable to have the variable name of optimum length.

Previous Article

Next Article