Golang ProgramsGolang Programs

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)
}

Variables Examples

1) Declaring an integer and string variable

The assignment of a value inline with the initialization of the variable.

package main

import (
    "fmt"
)

func main() {
    var i int = 10
    var s string = "Japan"
    fmt.Println(i)
    fmt.Println(s)
}


Sample output of above program, shown as below.
C:\golang\coding>go run example1.go
10
Japan

C:\golang\coding>

A variable in Go is initialized by var keyword.
In above example variables are assigned by name i, s and type integer, string respectively.
The assignment operator = signifies that the variable should be assigned a value of whatever is to the right of = .
The fmt standard library package uses the variable name i and s as a reference to the value of i and s.

2) Assignment after initialization

First a variable is initialized and then assigned a value later in program.

package main

import (
    "fmt"
)

func main() {
    var intVar int
    var strVar string

    intVar = 10
    strVar = "Australia"

    fmt.Println(intVar)
    fmt.Println(strVar)
}
Sample output of above program, shown as below.
C:\golang\coding>go run example1.go
10
Australia

C:\golang\coding>