How to Print the Values of Slices of Golang

To print the values of slices, you can use the fmt.Println() function. The fmt.Println() function prints one or more values, followed by a newline, to the standard output.

Here is an example of how to create a slice, take a sub-slice, and print the values of the original slice and its sub-slice.

package main

import (
  "fmt"
)

func main() {
  // Create a slice of integers
  numbers := []int{1, 2, 3, 4, 5}

  subSlice := numbers[1:4]

  // Print the values of the original slice and the sub-slice
  fmt.Println("Original slice:", numbers)
  fmt.Println("Sub-slice:", subSlice)
}

Output

Original slice: [1 2 3 4 5]
Sub-slice: [2 3 4]

To print the values of the slice one by one, you can use a for loop with the range keyword.

package main

import (
  "fmt"
)

func main() {
  // Create a slice of integers
  numbers := []int{1, 2, 3, 4, 5}

  // Take a sub-slice from the original slice
  subSlice := numbers[1:4]

  // Print the values of the original slice one by one
  fmt.Println("Original slice:")
  for index, value := range numbers {
    fmt.Printf("Index %d: %d\n", index, value)
  }

  // Print the values of the sub-slice one by one
  fmt.Println("Sub-slice:")
  for index, value := range subSlice {
    fmt.Printf("Index %d: %d\n", index, value)
  }
}

Output

Original slice:
Index 0: 1
Index 1: 2
Index 2: 3
Index 3: 4
Index 4: 5
Sub-slice:
Index 0: 2
Index 1: 3
Index 2: 4

That’s it.

Leave a Comment