Golang Tutorial

Fundamentals

Control Statements

Functions & Methods

Structure

Arrays & Slices

String

Pointers

Interfaces

Concurrency

var Keyword in Golang

The var keyword in Go is used to declare variables. It's one of the primary ways to define and initialize variables in Go, offering a variety of use cases and formats. In this tutorial, we'll explore different ways to use the var keyword for variable declaration and initialization.

1. Basic Declaration

With the var keyword, you can declare a variable without initializing it. The zero value of the variable's type will be assigned by default.

var name string
var age int

2. Declaration with Initialization

You can also declare a variable and provide an initial value:

var name string = "John"
var age int = 30

3. Type Inference

If you initialize a variable at the time of declaration, Go can infer the type of the variable from the provided value. In this case, you can omit the type:

var name = "John"
var age = 30  // The type of age will be inferred as int.

4. Declaring Multiple Variables

You can declare multiple variables of the same type in a single line:

var x, y, z int

Or with initialization:

var x, y, z int = 1, 2, 3

You can also mix types when using type inference:

var a, b, c = 1, false, "str"

5. Short Declaration

While this tutorial focuses on the var keyword, it's worth mentioning the short declaration operator :=, which is often used for local variable declaration. It infers the type of the variable from the right-hand side value:

name := "John"
age := 30

Note: The short declaration operator can only be used inside functions.

6. Package-level Variables

You can use the var keyword outside of functions to declare package-level variables:

package main

import "fmt"

var name = "John"

func main() {
    fmt.Println(name)
}

7. Zero Values

If a variable is declared using the var keyword without an explicit initial value, it is given its zero value:

  • int: 0
  • float64: 0
  • bool: false
  • string: ""
  • Pointers, functions, interfaces, slices, channels, and maps: nil

Key Takeaways:

  • The var keyword is used for variable declarations.
  • You can declare a variable with or without initialization.
  • Go can infer the type of a variable if it's initialized at the time of declaration.
  • For local variable declarations inside functions, the short declaration operator := is a common alternative to var.
  • Variables declared without an explicit initial value are given their zero value.

Understanding variable declaration is fundamental to Go programming. The flexibility provided by the var keyword, combined with type inference and the short declaration operator, allows developers to choose the most concise and clear method for their specific use cases.

  1. Declaring variables with var in Go:

    The var keyword is used to declare variables in Go.

    package main
    
    import "fmt"
    
    func main() {
        var age int
        var name string
    
        age = 25
        name = "John"
    
        fmt.Println("Name:", name)
        fmt.Println("Age:", age)
    }
    
  2. Zero-value initialization with var in Golang:

    When a variable is declared using var without an explicit initialization, it is set to its zero value.

    package main
    
    import "fmt"
    
    func main() {
        var age int
        var name string
    
        fmt.Println("Name:", name) // Zero value for string is an empty string
        fmt.Println("Age:", age)   // Zero value for int is 0
    }
    
  3. Scoping rules for var in Golang:

    The scope of a variable declared with var is limited to the block or function where it is declared.

    package main
    
    import "fmt"
    
    func main() {
        var outerVar int = 42
    
        if true {
            var innerVar int = 10
            fmt.Println("InnerVar:", innerVar)
        }
    
        fmt.Println("OuterVar:", outerVar)
        // fmt.Println("InnerVar:", innerVar) // Uncommenting this line will result in a compilation error
    }
    
  4. Golang var keyword vs short variable declaration:

    The var keyword is used for explicit variable declaration, while short variable declaration (:=) allows implicit type inference.

    package main
    
    import "fmt"
    
    func main() {
        var age int    // explicit declaration
        name := "John" // short variable declaration
    
        age = 25
    
        fmt.Println("Name:", name)
        fmt.Println("Age:", age)
    }
    
  5. Initializing multiple variables with var in Go:

    Multiple variables can be declared and initialized in a single var statement.

    package main
    
    import "fmt"
    
    func main() {
        var (
            age  int    = 25
            name string = "John"
        )
    
        fmt.Println("Name:", name)
        fmt.Println("Age:", age)
    }
    
  6. Constants and var keyword in Golang:

    Constants are declared using the const keyword, while variables are declared with var.

    package main
    
    import "fmt"
    
    const pi = 3.14
    
    func main() {
        var radius float64 = 5.0
        area := pi * radius * radius
    
        fmt.Println("Area:", area)
    }
    
  7. Global variables using var in Go:

    Global variables are declared outside any function and can be accessed throughout the package.

    package main
    
    import "fmt"
    
    var globalVar int = 42
    
    func main() {
        fmt.Println("GlobalVar:", globalVar)
    }
    
  8. var keyword in struct fields Golang:

    The var keyword is not commonly used for struct fields; instead, you can use a composite literal to create a struct with field values.

    package main
    
    import "fmt"
    
    type Person struct {
        Name string
        Age  int
    }
    
    func main() {
        // Using composite literal to create a struct
        person := Person{
            Name: "Alice",
            Age:  30,
        }
    
        fmt.Println("Person:", person)
    }