172

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

projects []Project  
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
fnr
  • 9,007
  • 5
  • 17
  • 16
  • 16
    besides `fmt.Println(projects)`? – Not_a_Golfer Jun 30 '14 at 11:47
  • 4
    Also: []Projects is a slice, not an array: http://golang.org/blog/go-slices-usage-and-internals – elithrar Jun 30 '14 at 12:02
  • Why did you all gave me -1 ? – fnr Jun 30 '14 at 12:51
  • 2
    @fnr sorry, but the reviewers probably felt the question was a easily solved by the doc. I have updated my answer to show it isn't always as obvious though. You can leave your question, it is a valid one. – VonC Jun 30 '14 at 12:57
  • 3
    @fnr - a -1 on this site means the question: "does not show research effort; it is unclear or not useful". So I see you tagged your question "go" and "arrays" and want to know "how to print" them. If I go to Google.com and search "go programming language tutorial arrays" I find a number of resources including [this](http://www.golang-book.com/6/index.htm) which looks like it might help. So if this does help, it shows you didn't research it much before posting. If this doesn't help, you need to call out sites like this you searched and explain why it wasn't helpful. – Mike Jul 23 '14 at 15:54
  • Does this answer your question? See https://stackoverflow.com/a/64292187/12817546. –  Oct 10 '20 at 10:04

8 Answers8

273

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.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • You could also use a `for` loop to to see the values which are in the slice `[]Project`. See https://stackoverflow.com/a/64292187/12817546. –  Oct 10 '20 at 10:23
47

For a []string, you can use strings.Join():

s := []string{"foo", "bar", "baz"}
fmt.Println(strings.Join(s, ", "))
// output: foo, bar, baz
jgillich
  • 71,459
  • 6
  • 57
  • 85
39

I prefer fmt.Printf("%+q", arr) which will print

["some" "values" "list"]

https://play.golang.org/p/XHfkENNQAKb

Pylinux
  • 11,278
  • 4
  • 60
  • 67
6

If you just want to see the values of an array without brackets, you can use a combination of fmt.Sprint() and strings.Trim()

a := []string{"a", "b"}
fmt.Print(strings.Trim(fmt.Sprint(a), "[]"))
fmt.Print(a)

Returns:

a b
[a b]

Be aware though that with this solution any leading brackets will be lost from the first value and any trailing brackets will be lost from the last value

a := []string{"[a]", "[b]"}
fmt.Print(strings.Trim(fmt.Sprint(a), "[]")
fmt.Print(a)

Returns:

a] [b
[[a] [b]]

For more info see the documentation for strings.Trim()

Eddie Curtis
  • 1,207
  • 8
  • 20
  • 1
    fmt.Printf(strings.Trim(fmt.Sprintf(a), "[]") is missing a paren on the right hand side. Thanks for the snippet. – pdbrito Apr 04 '17 at 08:32
6

I wrote a package named Pretty Slice. You can use it to visualize slices, and their backing arrays, etc.

package main

import pretty "github.com/inancgumus/prettyslice"

func main() {
    nums := []int{1, 9, 5, 6, 4, 8}
    odds := nums[:3]
    evens := nums[3:]

    nums[1], nums[3] = 9, 6
    pretty.Show("nums", nums)
    pretty.Show("odds : nums[:3]", odds)
    pretty.Show("evens: nums[3:]", evens)
}

This code is going produce and output like this one:

enter image description here


For more details, please read: https://github.com/inancgumus/prettyslice

Inanc Gumus
  • 25,195
  • 9
  • 85
  • 101
5

If you want to view the information in a slice in the same format that you'd use to type it in (something like ["one", "two", "three"]), here's a code example showing how to do that:

package main

import (
    "fmt"
    "strings"
)

func main() {
    test := []string{"one", "two", "three"}     // The slice of data
    semiformat := fmt.Sprintf("%q\n", test)     // Turn the slice into a string that looks like ["one" "two" "three"]
    tokens := strings.Split(semiformat, " ")    // Split this string by spaces
    fmt.Printf(strings.Join(tokens, ", "))      // Join the Slice together (that was split by spaces) with commas
}

Go Playground

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Gamelub
  • 51
  • 1
  • 1
4

fmt.Printf() is fine, but sometimes I like to use pretty print package.

import "github.com/kr/pretty"
pretty.Print(...)
akond
  • 15,865
  • 4
  • 35
  • 55
4

You could use a for loop to print the []Project as shown in @VonC excellent answer.

package main

import "fmt"

type Project struct{ name string }

func main() {
    projects := []Project{{"p1"}, {"p2"}}
    for i := range projects {
        p := projects[i]
        fmt.Println(p.name) //p1, p2
    }
}