“var” keyword in Golang

The utilization of the var keyword in Golang programming allows for the explicit declaration of variables.
In Golang, the storage and manipulation of data heavily rely on variables. The var keyword serves the purpose of explicitly declaring variables, requiring the specification of the variable’s name and, optionally, its type or initial value. This explicit declaration is essential for enhancing clarity and improving the readability of the code, as it unambiguously conveys the variable’s purpose and utilization within the program.

Example:

var x int // Declares a variable x of type int
var y string // Declares a variable y of type string

By using the var keyword, developers can create variables that are scoped to the function or package level, allowing for well-defined and controlled usage of these variables within the program.

Golang is a Statically Typed Language
The Golang programming language is statically typed, meaning that developers must specify the data type of each variable when declaring it. This ensures that the type of every variable is known at compile time, rather than at runtime. This approach brings various benefits, including type safety, improved performance, and enhanced code clarity. Type safety helps the compiler detect type mismatches and potential errors at compile time, reducing runtime errors and improving code reliability. Furthermore, the ability to determine types at compile time allows the compiler to optimize the generated code for better performance. The explicit type declarations also make the code more readable and understandable, as the data types of variables are immediately clear to anyone reading the code.

var a int = 10 
// Declares an integer variable a with an initial value of 10
var b float64 = 20.5 
// Declares a floating-point variable b with an initial value of 20.5

Explicit Type Declaration:

var c bool = true // Declares a boolean variable c with an initial value of true

Type Inference:

var d = "Hello, Golang!" // The type string is inferred from the initial value

In cases where the type is obvious from the context, type inference can make the code more concise without sacrificing readability.

Let’s break down the syntax and explain each component involved in declaring a variable with the var keyword in Golang:

1. Variable Declaration Syntax

var identifier type = expression (optional)

Here’s a detailed explanation of each part:

1.1 “var”

The keyword var implies to the compiler that you are declaring a variable. It is utilized to create a new variable with a specific type and an optional initial value.

Example :

var age int

1.2 “identifier”

The name you select for your variable is the identifier. It is important that it is descriptive and adheres to Go’s naming conventions.

 

  • The identifier must begin with a letter (a-z or A-Z) or an underscore (_), and it can include letters, numbers (0-9), and underscores.
  • It is essential to avoid using reserved keywords such as func, package, or var for the identifier.

Example:

var userName string

1.3 “type”

The data type of a variable is specified by the type. Golang is statically typed, which means that the type of each variable must be defined. Golang has a variety of built-in data types and allows for the creation of custom types.

1.3.1 Examples of built-in types include: -

  • int: denotes integer numbers (e.g., 1, 100)
  • string: represents text (e.g., “Hello”, “World”)
  • bool: indicates boolean values (true or false)
  • float32, float64: signify floating-point numbers (e.g., 3.14, 2.718)
var age int           // integer type
var isActive bool     // boolean type
var price float64     // floating-point type
var message string    // string type

1.3.2 Custom types in Golang include: -

  • Structs: these are user-defined data types that group together fields. 
  • Interfaces: these define a set of method signatures. Interfaces with zero method signatures is an empty interface.
1.3.2.1 Struct Example:
// Define a struct Circle
type Circle struct {
   radius float64
}
func main() {
// Create a variable of Circle struct type and Initialise the Circle instance
   var c Circle = Circle{radius: 5}
   // Access and print the radius
   fmt.Println("Radius of circle:", c.radius)
}

For the complete program, Please visit our GitHub repository.

1.3.2.2 Interface with method signatures Example :
// Define an interface
type Shape interface {
   area() float64
}
// Define a struct Circle
type Circle struct {
   radius float64
}
// Implementing Shape interface for Circle
func (c Circle) area() float64 {
   return math.Pi * c.radius * c.radius
}
func main() {
   // Create an instance of Circle
   circle := Circle{radius: 5}
   // Create a variable of Shape interface type & assign the Circle instance to the Shape interface variable
   var shape Shape = circle
   // Call area method on Circle using Shape interface
   area := shape.area()
   // Print area of circle
   fmt.Printf("Area of circle: %.2f\n", area)
}

For the complete program, Please visit our GitHub repository.

1.3.2.3 Empty Interface Example :
func main() {
   // Declare a variable of empty interface type
   var x interface{}
   // Assign different values to the empty interface variable
   x = 42          // int
   fmt.Println("Type:", getType(x), ", Value:", x)
   x = "hello"     // string
   fmt.Println("Type:", getType(x), ", Value:", x)
   x = true        // bool
   fmt.Println("Type:", getType(x), ", Value:", x)
   x = struct{}{}  // empty struct
   fmt.Println("Type:", getType(x), ", Value:", x)
}
// Function to get the type of the interface value
func getType(i interface{}) string {
   return fmt.Sprintf("%T", i)
}

For the complete program, Please visit our GitHub repository.

1.4 "expression" (optional)

  • The expression allows you to assign an initial value to the variable when it is defined. If you indicate an initial value, it should be appropriate for the declared data type.
  • When no initial value is given, the variable will be set to the default value of its type.
  • For e.g., 0 for int, ” ” for string, and false for bool.

Following is the expression:

var age int = 25              // initializes age with 25
var isActive bool = true      // initializes isActive with true
var price float64 = 19.99     // initializes price with 19.99
var message string = "Hello"  // initializes message with "Hello"

The following examples demonstrate different methods of variable declaration: explicit declaration, type inference, and multiple variables of the same type declared in a single line:

 

Example :

2. var keyword declaration

func main() {
   // Variables with explicit type declarations
   var age int = 30
   var name string = "James"
   var isLoggedIn bool = false
   // Variables with type inference
   var x = 10                    // Inferred type: int
   var message = "Hello, world!" // Inferred type: string
   var success = true            // Inferred type: bool
   // Multiple variables of the same type in a single line
   var width, height int = 100, 200
   // Print the values of the variables
   fmt.Println("Explicit type declarations:")
   fmt.Println("Age:", age)
   fmt.Println("Name:", name)
   fmt.Println("Is Logged In:", isLoggedIn)
   fmt.Println("\nType inference:")
   fmt.Println("x:", x)
   fmt.Println("Message:", message)
   fmt.Println("Success:", success)
   fmt.Println("\nMultiple variables:")
   fmt.Println("Width:", width, "Height:", height)
}
// Output : 
// Explicit type declarations:
// Age: 30
// Name: James
// Is Logged In: false
// Type inference:
// x: 10
// Message: Hello, world!
// Success: true
// Multiple variables:
// Width: 100 Height: 200

For the complete program, Please visit our GitHub repository.

2.1 When to use var:

Complex Data Types:
When initializing variables with complex structures or non-trivial initial values.

func main() {
   var customerData struct {
       Name    string
       Age     int
       Address string
   } = struct {
       Name    string
       Age     int
       Address string
   }{"John Doe", 30, "123 Main St"}
   fmt.Println(customerData)
}
// {John Doe 30 123 Main St}

2.2 Global Variables:

When declaring variables at the package level to ensure they are accessible globally and maintain clarity about their scope.

package main
import "fmt"
var globalCounter int = 0
func main() {
   IncrementGlobalCounter()
}
func IncrementGlobalCounter() {
   globalCounter++
   fmt.Println(globalCounter)
} // output : 1 

3. Short Variable Declaration (:=)

  • Explanation:
    • Short Variable Declaration: Inside functions, you can use the := operator for concise variable declaration and initialization.
    • Example:
func main() {
   // Short variable declaration example
   name := "Alice"
   age := 30
   isLoggedIn := false
   fmt.Printf("Name\t:%v\n", name)
   fmt.Printf("Age\t:%v\n", age)
   fmt.Printf("LoggedIn:%v\n", isLoggedIn)
}
// output 
// Name            :Alice
// Age             :30
// LoggedIn        :false

For the complete program, Please visit our GitHub repository.

4. Difference between “var” keyword declaration and short variable “:=” declaration:

Aspect
System Cron Job
Golang Cron Job
Syntax
var identifier type = value
identifier := value
Explicit Type
Required (if no value is provided)
Inferred from the value
Initialization
Optional
Mandatory
Scope
Global and local
Local (within functions)
Zero Value Initialization
Yes, if no value is provided
Not applicable (initial value is mandatory)
Multiple Declarations
Supported
Supported
Readability
Can be more readable with explicit type
Can be more concise
Example 1
var age int = 30
age := 30
Example 2
var name string (zero value is "")
name := "Alice"
Example 3
var arr []int (zero value is nil)
var arr []int (zero value is nil)
Global Declaration
Yes
No
Preferred Usage
When explicit type is needed or for global vars
For local variables with immediate initialization
Verbosity
More verbose due to explicit type
More concise due to type inference

4. Difference between “var” keyword declaration and short variable “:=” declaration:

  • Aspect:
    • Syntax

    • Explicit Type

    • Initialization
    • Scope
    • Zero Value Initialization
    • Multiple Declarations
    • Readability
    • Example 1
    • Example 2
    • Example 3
    • Global Declaration
    • Preferred Usage
    • Verbosity
  • var Declaration:

    • var identifier type = value

    • Required (if no value is provided)

    • Optional
    • Global and local
    • Yes, if no value is provided
    • Supported
    • Can be more readable with explicit type
    • var age int = 30
    • var name string (zero value is “”)
    • var arr []int (zero value is nil)
    • Yes
    • When explicit type is needed or for global vars
    • More verbose due to explicit type
  • Short Variable Declaration (:=):
    • identifier := value

    • Inferred from the value

    • Mandatory

    • Local (within functions)
    • Not applicable (initial value is mandatory)
    • Supported
    • Can be more concise
    • age := 30
    • name := “Alice”
    • arr := []int{} (empty slice)
    • No
    • For local variables with immediate initialization
    • More concise due to type inference