如何打印切片的值

huangapple go评论77阅读模式
英文:

How to print the values of slices

问题

我想要查看切片中的值。我该如何打印它们?

projects []Project 
英文:

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

projects []Project 	

答案1

得分: 273

你可以尝试使用go fmt中的%v%+v%#v动词:

fmt.Printf("%v", projects)

如果你的数组(或切片)包含struct(比如Project),你将看到它们的详细信息。
为了更精确地打印对象,你可以使用%#v以Go语法的形式打印对象,就像字面量一样:

  • %v:以默认格式打印值。
  • %+v:在打印结构体时,加号标志(%+v)会添加字段名。
  • %#v:以Go语法表示的值。

对于基本类型,fmt.Println(projects)就足够了。

注意:对于指针的切片,即[]*Project(而不是[]Project),最好定义一个String()方法,以便显示你想要看到的内容(否则你只会看到指针地址)。可以参考这个play.golang示例

英文:

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.

答案2

得分: 47

对于[]string,你可以使用strings.Join()函数:

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

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

<!-- language: golang -->

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

答案3

得分: 39

我更喜欢使用fmt.Printf("%+q", arr),它会打印出:

["some" "values" "list"]

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

英文:

I prefer fmt.Printf(&quot;%+q&quot;, arr) which will print

[&quot;some&quot; &quot;values&quot; &quot;list&quot;]

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

答案4

得分: 6

如果你只想看到一个没有括号的数组值,你可以使用fmt.Sprint()strings.Trim()的组合。

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

返回结果:

a b
[a b]

需要注意的是,使用这种方法会导致第一个值的前导括号丢失,最后一个值的尾随括号丢失。

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

返回结果:

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

有关更多信息,请参阅strings.Trim()的文档。

英文:

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{&quot;a&quot;, &quot;b&quot;}
fmt.Print(strings.Trim(fmt.Sprint(a), &quot;[]&quot;))
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{&quot;[a]&quot;, &quot;[b]&quot;}
fmt.Print(strings.Trim(fmt.Sprint(a), &quot;[]&quot;)
fmt.Print(a)

Returns:

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

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

答案5

得分: 6

我写了一个名为Pretty Slice的包。你可以使用它来可视化切片及其支持的数组等。

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

这段代码将产生以下输出:

如何打印切片的值


更多详情,请阅读:https://github.com/inancgumus/prettyslice

英文:

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

package main

import pretty &quot;github.com/inancgumus/prettyslice&quot;

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

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

This code is going produce and output like this one:

如何打印切片的值


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

答案6

得分: 5

如果您想以与键入相同的格式查看切片中的信息(类似于["one", "two", "three"]),以下是一个代码示例,展示了如何实现:

package main

import (
	"fmt"
	"strings"
)

func main() {
	test := []string{"one", "two", "three"} 	// 数据切片
	semiformat := fmt.Sprintf("%q\n", test)		// 将切片转换为类似于["one" "two" "three"]的字符串
	tokens := strings.Split(semiformat, " ")	// 使用空格拆分该字符串
	fmt.Printf(strings.Join(tokens, ", "))		// 使用逗号将拆分的切片重新连接起来
}

Go Playground

英文:

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

package main

import (
	&quot;fmt&quot;
	&quot;strings&quot;
)

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

Go Playground

答案7

得分: 4

fmt.Printf()是可以的,但有时我喜欢使用pretty print包

import "github.com/kr/pretty"
pretty.Print(...)
英文:

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

import &quot;github.com/kr/pretty&quot;
pretty.Print(...)

答案8

得分: 4

你可以使用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
    }
}
英文:

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

package main

import &quot;fmt&quot;

type Project struct{ name string }

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

huangapple
  • 本文由 发表于 2014年6月30日 19:44:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/24489384.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定