Variable Declarations in Go

Photo by Chinmay B on Unsplash

Variable Declarations in Go

Go provides several ways to declare variables, each suited for different situations.

1. Using the var Keyword

Syntax:

var variableName type
var variableName type = value

When to use:

  • When you want to specify the type explicitly.

  • When you need to declare a package-level variable.

  • When you initialize a variable with a zero value.

Exercise: Declare a string variable called greeting with a value "Hello, World!" and print it.

Solution:

package main

import "fmt"

var greeting string = "Hello, World!"

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

2. Using Short Declaration :=

Syntax:

variableName := value

When to use:

  • When you're inside a function and you want a concise way to declare and initialize.

  • When you want the compiler to infer the type based on the given value.

    You cannot use the short declaration (:=) outside of a function in Go. If you attempt to do so, the Go compiler will throw an error. The short declaration is designed to provide concise variable declaration and initialization inside functions.

Exercise: Inside the main function, declare a variable num with a value of 42 and print it.

Solution:

package main

import "fmt"

func main() {
    num := 42
    fmt.Println(num)
}

3. Using the var Keyword with Initializers

Syntax:

var variableName = value

When to use:

  • When you want the compiler to infer the type but you're not inside a function or prefer a slightly more verbose syntax.

Exercise: Declare a variable pi at the package level with a value of 3.14 and print it in the main function.

Solution:

package main

import "fmt"

var pi = 3.14

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

4. Declaring Multiple Variables

Syntax:

var (
    variable1 type1
    variable2 type2 = value2
    variable3 = value3
)

When to use:

  • When you need to declare multiple variables in a grouped fashion, for clarity and organization.

Exercise: Declare three variables: an integer a with value 10, a string b with value "Go", and a float c with value 5.5, then print them.

Solution:

package main

import "fmt"

var (
    a int = 10
    b     = "Go"
    c     = 5.5
)

func main() {
    fmt.Println(a, b, c)
}

5. Using Pointers

Syntax:

var variableName *Type

When to use:

  • When you need to store the memory address of a value.

Exercise: Declare a pointer to an integer, assign the address of an integer variable x with value 100 to the pointer, and print the value stored at that address.

Solution:

package main

import "fmt"

func main() {
    var x int = 100
    var ptr *int
    ptr = &x
    fmt.Println(*ptr)
}

References

  1. Pointers in Go