Von*_*onC 142
你可以尝试%v,%+v或%#v动词去FMT:
fmt.Printf("%v", projects)
Run Code Online (Sandbox Code Playgroud)
如果您的数组(或此处切片)包含struct(如Project),您将看到它们的详细信息.
为了更加精确,您可以使用%#vGo-syntax打印对象,如文字所示:
%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
Run Code Online (Sandbox Code Playgroud)
对于基本类型,fmt.Println(projects)就足够了.
注意:对于一片指针,即[]*Project(而不是[]Project),最好定义一个String()方法,以便准确显示您想要查看的内容(或者您将只看到指针地址).
请参阅此play.golang示例.
jgi*_*ich 18
对于a []string,您可以使用strings.Join():
s := []string{"foo", "bar", "baz"}
fmt.Println(strings.Join(s, ", "))
// output: foo, bar, baz
Run Code Online (Sandbox Code Playgroud)
我希望fmt.Printf("%+q", arr)可以打印
["some" "values" "list"]
Run Code Online (Sandbox Code Playgroud)
https://play.golang.org/p/XHfkENNQAKb
如果您只想查看不带括号的数组的值,可以使用fmt.Sprint()和的组合strings.Trim()
a := []string{"a", "b"}
fmt.Print(strings.Trim(fmt.Sprint(a), "[]"))
fmt.Print(a)
Run Code Online (Sandbox Code Playgroud)
返回:
a b
[a b]
Run Code Online (Sandbox Code Playgroud)
但请注意,使用此解决方案时,第一个值中的任何前括号都将丢失,最后一个值中的任何尾括号都将丢失
a := []string{"[a]", "[b]"}
fmt.Print(strings.Trim(fmt.Sprint(a), "[]")
fmt.Print(a)
Run Code Online (Sandbox Code Playgroud)
返回:
a] [b
[[a] [b]]
Run Code Online (Sandbox Code Playgroud)
小智 6
如果您想以与键入相同的格式查看切片中的信息(例如["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
}
Run Code Online (Sandbox Code Playgroud)
我写了一个名为 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)
}
Run Code Online (Sandbox Code Playgroud)
这段代码将像这样生成和输出:
更多详情请阅读: https: //github.com/inancgumus/prettyslice