英文:
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{"foo", "bar", "baz"}
fmt.Println(strings.Join(s, ", "))
// output: foo, bar, baz
答案3
得分: 39
我更喜欢使用fmt.Printf("%+q", arr)
,它会打印出:
["some" "values" "list"]
https://play.golang.org/p/XHfkENNQAKb
英文:
I prefer fmt.Printf("%+q", arr)
which will print
["some" "values" "list"]
答案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{"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()
答案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 "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
答案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, ", ")) // 使用逗号将拆分的切片重新连接起来
}
英文:
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
}
答案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 "github.com/kr/pretty"
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 "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
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论