Rabi Siddique
201 words
1 minutes
Variables in Golang
2023-01-05

In Go, a variable is a name that refers to a value stored in memory. There are two primary ways to declare a new variable in Go: using the var keyword and omitting the type.

Using the var Keyword#

You can declare a variable with an explicit type using the var keyword:

package main

import "fmt"

func variables() {
    // Declaring variables with explicit types
    var x int = 10
    var y float64 = 3.14
    var z string = "Hello, World!"
    fmt.Println(x, y, z) // Output: 10 3.14 Hello, World!
}

Omitting the Type#

You can also declare a variable without specifying its type. In this case, the type is inferred from the value:


func variables() {
    // Declaring variables without explicit types
    a := 10
    b := 3.14
    c := "Hello, World!"
    fmt.Println(a, b, c) // Output: 10 3.14 Hello, World!
}

Zero Value Initialization#

If you declare a variable without initializing it, Go assigns it a zero value based on its type:

func variables() {
    // Declaring variables without initialization
    var p int    // p is initialized to 0
    var q string // q is initialized to ""
    var r bool   // r is initialized to false
    fmt.Println(p, q, r) // Output: 0  false
}

Variables in Golang
https://rabisiddique.com/posts/variables-in-golang/
Author
Rabi Siddique
Published at
2023-01-05