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.
Example
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.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.