HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoCritical

How to print the values of slices

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
sliceshowtheprintvalues

Problem

I want to see the values which are in the slice. How can I print them?

projects []Project

Solution

You can try the %v, %+v or %#v verbs of go fmt:

fmt.Printf("%v", projects)


If your array (or here slice) contains struct (like Project), you will see their details.

For more precision, you can use %#v to print the object using Go-syntax, as for a literal:

%v  the value in a default format.
    when printing structs, the plus flag (%+v) adds field names
%#v a Go-syntax representation of the value


For basic types, fmt.Println(projects) is enough.

Note: for a slice of pointers, that is []*Project (instead of []Project), you are better off defining a String() method in order to display exactly what you want to see (or you will see only pointer address).

See this play.golang example.

Code Snippets

fmt.Printf("%v", projects)
%v  the value in a default format.
    when printing structs, the plus flag (%+v) adds field names
%#v a Go-syntax representation of the value

Context

Stack Overflow Q#24489384, score: 296

Revisions (0)

No revisions yet.