172

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

projects []Project  
6
  • 16
    besides fmt.Println(projects)? Jun 30, 2014 at 11:47
  • 4
    Also: []Projects is a slice, not an array: golang.org/blog/go-slices-usage-and-internals
    – elithrar
    Jun 30, 2014 at 12:02
  • Why did you all gave me -1 ?
    – fnr
    Jun 30, 2014 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, 2014 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 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, 2014 at 15:54

8 Answers 8

275

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.

1
48

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

s := []string{"foo", "bar", "baz"}
fmt.Println(strings.Join(s, ", "))
// output: foo, bar, baz
42

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

["some" "values" "list"]

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

3
  • 2
    How to get array with comma separator ??
    – Shoba
    Dec 6, 2019 at 13:11
  • ¯\_(ツ)_/¯ If you find short solution please add it as an answer to this question. I’m betting that is what most people are looking for.
    – Pylinux
    Dec 7, 2019 at 14:03
  • strings.ReplaceAll(fmt.Sprintf("%+q", arr), "\" \"", "\",\"")
    – dareniott
    Mar 22, 2022 at 16:35
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()

1
  • 1
    fmt.Printf(strings.Trim(fmt.Sprintf(a), "[]") is missing a paren on the right hand side. Thanks for the snippet.
    – pdbrito
    Apr 4, 2017 at 8:32
6

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

1
  • Wrong. "%q" is hex format. Dec 16, 2021 at 19:19
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

0
4

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

import "github.com/kr/pretty"
pretty.Print(...)
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
    }
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.