The variable in Go points to some memory location that stores some type of value.
A variable is only a name given to a storage space that the applications can control. Each variable in Go includes a particular type, which determines the size and layout in the memory.
A few rules of Go variables are:
- The name of a variable could be composed of letters, digits, and the underscore character.
- It has to start with a letter or an underscore.
- Upper and lowercase letters are different because Go is case-sensitive.
- It is possible to declare a number of variables at the same time.
- Go will evaluate the kind of all initialized variables.
Declaring go variable
This is how Go variables are declared:
var <variable_name> <type>
So, you have to use the “var” keyword.
The type parameter(from the above syntax) signifies the sort of value which may be kept in the memory place.
The basic type of variable includes:
- byte
- int
- float32
- complex64
- boolean
- user-defined object etc.
An example of declaring the variable in Go
You may declare variables in different ways in Go. Follow are a few examples:
var x, y var x, y, z int var chr byte var amount float32
All the above are valid declarations in Go.
Declaring the variables with values
This is how you may assign a value to the variable at the time of declaration:
var <var_name> = <var_value>
For example:
var x = 20
Omitting the var keyword as declaring variables
You may also use the shorthand for declaring and initializing the variable in Go. For that, use the := as shown below:
<var_name > := <var_value>
An example Go program of variable
In the example below, we have declared a variable. This is followed by assigning a value and then displaying the value:
package main import "fmt" func main() { var x int x = 100 fmt.Println(x) }
The output:
100
Another example with different variations
See this example where we declared variables in various ways and displayed values:
The output:
Some Value
5 10
Another example with var
This example shows declaring without var keyword as well.
package main import "fmt" func main() { var b = true fmt.Println(b) ani := "lion" fmt.Println(f) }
The output:
true
lion
Note: Variables declared with No initial value will have of 0 for numeric types, false for the Boolean and empty string for strings.