Welcome to Golang Programs, Get the best new programs in your inbox, daily.

Variables

Naming a variable properly is an important part of software development. Names must start with a letter and may contain letters, numbers, or the underscore symbol (_). The Go compiler doesn't care what you name a variable, but you should choose names that clearly describe the variable's purpose.

package main
import "fmt"
func main(){
  var x int
  x=10
  fmt.Println(x)
  var y int = 20
  fmt.Println(y)
  z:=30
  fmt.Println(z)
  var Speed, distanCe, _time, CalCulation=10,20,30,40 // Variable Name Conventions
  fmt.Println(Speed,distanCe,_time,CalCulation)
}

At the time of variable declaration we may omit either type or expression for the initialization, but we can't specify at least one. If the type is omitted from the variable declaration, it is determined from the expression used for initialization. If the expression is omitted, system assigns the initial value is 0 for numeric variable types, false for boolean variable type, and "" for string variable type. Within a function, an alternate form called a short variable declaration may be used to declare and initialize local variables. It takes the form name := expression, and the type of name is determined by the type of expression.

package main
import "fmt"
func main(){
    firstname,lastname,age,Married:="John","Doe",25,false
    fmt.Println(firstname,lastname,age,Married)
}

Variables declared outside the main function are accessible from other fucntions also.

package main
import "fmt"
var x int = 10
func main(){
    fmt.Println(x)
    test()
}
func test(){
    fmt.Println(x)
}

Go also has another shorthand when you need to define multiple variables.

package main
import "fmt"
var (
a = 5
b = 10
c = 15
)
func main(){
    fmt.Println(a,b,c)
}