简体   繁体   English

如何打印切片的值

[英]How to print the values of slices

I want to see the values which are in the slice.我想查看切片中的值。 How can I print them?我怎样才能打印它们?

projects []Project  

You can try the %v , %+v or %#v verbs of go fmt :你可以试试go fmt%v%+v%#v动词:

fmt.Printf("%v", projects)

If your array (or here slice ) contains struct (like Project ), you will see their details.如果您的数组(或这里的 slice )包含struct (如Project ),您将看到它们的详细信息。
For more precision, you can use %#v to print the object using Go-syntax, as for a literal:为了更精确,您可以使用%#v使用 Go 语法打印对象,就像文字一样:

%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.对于基本类型, fmt.Println(projects)就足够了。


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).注意:对于一个指针片段,即[]*Project (而不是[]Project ),最好定义一个String()方法以准确显示您想要看到的内容(或者您将只看到指针地址)。
See this play.golang example .请参阅此play.golang 示例

For a []string , you can use strings.Join() :对于[]string ,您可以使用strings.Join()

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

I prefer fmt.Printf("%+q", arr) which will print我更喜欢fmt.Printf("%+q", arr)它将打印

["some" "values" "list"]

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

If you just want to see the values of an array without brackets, you can use a combination of fmt.Sprint() and strings.Trim()如果只想查看没有括号的数组的值,可以结合使用fmt.Sprint()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()有关更多信息,请参阅strings.Trim()的文档

fmt.Printf() is fine, but sometimes I like to use pretty print package . fmt.Printf()很好,但有时我喜欢使用漂亮的打印包

import "github.com/kr/pretty"
pretty.Print(...)

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:如果您想以与输入时使用的格式相同的格式查看切片中的信息(类似于["one", "two", "three"] ),这里有一个代码示例,展示了如何执行此操作:

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去游乐场

I wrote a package named Pretty Slice.我写了一个名为 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:这段代码将像这样产生和输出:

在此处输入图片说明


For more details, please read: https://github.com/inancgumus/prettyslice更多详情请阅读: https : //github.com/inancgumus/prettyslice

You could use a for loop to print the []Project as shown in @VonC excellent answer.您可以使用for循环来打印[]Project ,如@VonC 优秀答案所示。

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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM