![]() |
VOOZH | about |
Variables are names that hold data which can change while the program is running. They let you store and use information in your program. For Example:
The number is: 10
Explanation:
Valid examples:
Geeks, geeks, _geeks23
Invalid examples:
123Geeks, 23geeks
In Go language variables are created in two different ways:
Variables can be declared using the var keyword by specifying the variable name, type, and initial value.
var variable_name type = expression
Example: Variable Declaration with Type Inference
The value of myvariable1 is : 20 The type of myvariable1 is : int The value of myvariable2 is : GeeksforGeeks The type of myvariable2 is : string The value of myvariable3 is : 34.800000 The type of my...
If the expression is removed, the variable holds the zero-value of its type:
Example:
myvariable1: 0 myvariable2: myvariable3: 0.000000
In Go, you can declare and initialize several variables of the same type in one line, which makes the code shorter and easier to read.
Output
a: 2, b: 45, c: 67
Multiple variables of different types can be declared in a single line. If the type is not specified, Go automatically assigns a type based on the value.
Output
a: 2 (int), b: GFG (string), c: 67.560000 (float64)
Variables can be initialized using a function that returns more than one value, allowing you to handle multiple results at once.
First number: 5 Second number: 10
Explanation:
The local variables which are declared and initialize in the functions are declared by using short variable declaration.
variable_name := expression
Note: Please don't confuse in between := and = as := is a declaration and = is assignment.
Important Points: In the above expression, the type of the variable is determined by the type of the expression.
myvar1: 39 (int) myvar2: GeeksforGeeks (string) myvar3: 34.670000 (float64)
Multiple local variables of the same type can be declared and initialized in a single line using the short variable declaration :=
Output
myvar1: 800 (int)
myvar2: 34 (int)
myvar3: 56 (int)
Multiple local variables of different types can be declared and initialized in a single line using the short variable declaration :=, and Go automatically determines their types from the values.
Output
myvar1: 800 (int)
myvar2: Geeks (string)
myvar3: 47.560000 (float64)
Variables can be initialized using a function that returns multiple values, and the short declaration := can be used to store them in a single line.
Number: 7 Text: GoLang
Explanation:
A short variable declaration works like an assignment only if at least one variable is new in the same block.
The value of myvar1 and myvar2 is : 39 100 The value of myvar3 and myvar2 is : 45 100