Go variable examples

In this example, we will show you how to declare and use variables in Go with examples.

Variables are used to store values. They are labels given to the values. Go uses the var keyword to declare a list of variables. We can also use the := shorthand syntax to declare variables.

1. Go declare variable example

In the example, we declare and initialize two variables. Later, we print them.


package main

import "fmt"

func main() {

    var i int = 10
    var w float64 = 10.5

    fmt.Println(i)
    fmt.Println(w)
}

Output:

10
10.5

2. Go declare multiple variables example

With the var keyword, we can declare multiple variables at once.

The below example shows how to declare multiple variables with var.


package main

import "fmt"

func main() {

    var i, j, k = 1, 2, 3

    var (
        firstName       = "John"
        lastName = "Cena"
    )

    fmt.Println(i, j, k)
    fmt.Printf("%s  %s\n", firstName, lastName)
}

Output:

1 2 3
John  Cena

3. Go shorthand variable declaration example

Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type.

The example declares two variables with the shorthand notation.


package main

import "fmt"

func main() {

    name := "John"
    age := 24

    fmt.Println(name, age)
}

Output:

John 24

4. One more Go variable example


package main

import "fmt"

func main() {

    var a = "string"
    fmt.Println(a)

    var b, c int = 3, 4 // Go declare multiple variables
    fmt.Println(b, c)

    var d = true
    fmt.Println(d)

    var e int
    fmt.Println(e)

    f := "apple" // Go shorthand variable declaration
    fmt.Println(f)
}

Output:

string
3 4
true
0
apple

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course