Welcome To Golang By Example

Print an array or slice elements in Go (Golang)

Overview

The way we print an array or slice is same. Let’s look at both one by one

Print a Slice

Print slice elements together

Using

package main
import "fmt"
func main() {
    numbers := []int{1, 2, 3}
    fmt.Println(numbers)
    fmt.Printf("Numbers: %v", numbers)
}

Output

[1 2 3]
Numbers: [1 2 3]

Print individual slice elements

Using

package main
import "fmt"
func main() {
    numbers := []int{1, 2, 3}
    for _, num := range numbers {
        fmt.Println(num)
    }
}

Output

1
2
3

Print a Array

Print array elements together

Using

package main
import "fmt"
func main() {
    numbers := [3]int{1, 2, 3}
    fmt.Println(numbers)
    fmt.Printf("Numbers: %v", numbers)
}

Output

[1 2 3]
Numbers: [1 2 3]

Print individual array elements:

Using

package main
import "fmt"
func main() {
    numbers := [3]int{1, 2, 3}
    for _, num := range numbers {
        fmt.Println(num)
    }
}

Output

1
2
3