Go Example: Variables

1. Introduction

Variables are a fundamental aspect of any programming language, acting as containers for storing data values. In Go, variables are explicitly declared and used by the compiler to understand the type of data the program intends to work with. This blog post will introduce the concept of variables in Go through examples.

Variables in Go are declared using the var keyword or through shorthand syntax within functions.

2. Program Steps

1. Declare variables using the var keyword.

2. Use shorthand syntax for variable declaration within a function.

3. Initialize variables with values.

4. Print the values of variables.

3. Code Program

package main

import "fmt"

func main() {
	// Step 1: Declare a variable using the var keyword
	var a string = "initial"
	fmt.Println(a)

	// Step 2: Use shorthand syntax for declaring and initializing a variable
	b := "short"
	fmt.Println(b)

	// Step 3: Declare multiple variables at once
	var c, d int = 1, 2
	fmt.Println(c, d)

	// Declare a variable with inferred type
	var e = true
	fmt.Println(e)

	// Step 4: Declare a variable without initialization (will have zero value)
	var f int
	fmt.Println(f)

	// Step 5: Print the values of the variables
	var g int
	fmt.Println(g)

	var h float64
	fmt.Println(h)

	var i bool
	fmt.Println(i)

	var j string
	fmt.Println(j)
}

Output:

initial
short
1 2
true
0
0
0
false

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" - Imports the Format package for printing formatted output.

3. Variables a, b, c, d, e, and f are declared and initialized with the var keyword and shorthand assignment (:=). These variables are given types explicitly or inferred by the compiler.

4. Variables g, h, i, and j are declared without initial values and therefore are assigned zero values by default, which are 0, 0.0, false, and "" (empty string) respectively.

5. fmt.Println is used within the main function to print the variables' values to the console.

6. The output shows the initial values of each variable, demonstrating both the declaration and the zero value concept in Go.