Golang: Print Slice, Array

By Xah Lee. Date: . Last updated: .

Here's how to print Slice or Array .

Print Slice, Array

fmt.Printf("%v\n", slice)
Print slice in human readable form . Sample output: [3 4 5]
fmt.Printf("%#v\n", slice)
Print slice in golang syntax. Sample output: []int{3, 4, 5}
package main

import "fmt"

func main() {

	var sl = []int{3, 4, 5}

	// print it normally
	fmt.Printf("%v\n", sl) // [3 4 5]

	// print in golang syntax
	fmt.Printf("%#v\n", sl) // []int{3, 4, 5}

}

Print Slice One Element Per Line

To print each member on a line, you have to write a loop. 〔see Golang: loop

package main

import "fmt"

func printSlice(sliceX []string) error {
	for k, v := range sliceX {
		fmt.Printf("%v %v\n", k, v)
	}
	return nil
}

// --------------------------------------------------
// test

func main() {

	var fileList = []string{
		"dog.html",
		"cat.html",
		"rabbit.html",
	}

	printSlice(fileList)
}

/*
prints

0 dog.html
1 cat.html
2 rabbit.html

*/

Golang, Print

Golang, array and slice