[英]How can I get/print the content of a slice of array pointers?
I have the following struct and function:我有以下结构和功能:
type RayTrace struct {
gorm.Model
Var1 float64 `json:"var1"`
Var2 float64 `json:"var2"`
Var3 float64 `json:"var3"`
UserID uint `json:"user_id"`
}
...
// GetRaytracesFor function
func GetRaytracesFor(id uint) []*RayTrace {
raytraces := make([]*RayTrace, 0)
err := GetDB().Table("ray_traces").Where("user_id = ?", id).Last(&raytraces).Error
if err != nil {
return nil
}
return raytraces
}
How can I get/print the data returned from the db call?如何获取/打印从 db 调用返回的数据?
Thanks!谢谢!
I assume you're asking how to print the values of slice of pointers, not the address.我假设您问的是如何打印指针切片的值,而不是地址。 In this case, using
fmt.Println(raytraces)
or fmt.Printf("%v", raytraces) // or %+v or %#v
will return the addresses.在这种情况下,使用
fmt.Println(raytraces)
或fmt.Printf("%v", raytraces) // or %+v or %#v
将返回地址。
You might want to see similar question golang how to print struct value with pointer .您可能希望看到类似的问题golang how to print struct value with pointer 。
Basically, you need to print the fields manually.基本上,您需要手动打印字段。 Here's some different ways to do it:
这里有一些不同的方法来做到这一点:
func GetRaytracesFor(id uint) []*RayTrace {
raytraces := make([]*RayTrace, 0)
err := GetDB().Table("ray_traces").Where("user_id = ?", id).Last(&raytraces).Error
if err != nil {
return nil
}
for _, raytrace := range raytraces {
// before dereferencing pointer, check if nil
if raytrace == nil {
fmt.Println("<nil>")
continue
}
// notice the * before raytrace
fmt.Printf("%+v\n", *raytrace)
}
return raytraces
}
RayTrace
implements fmt.Stringer
RayTrace
实现fmt.Stringer
// implements fmt.Stringer
func (r RayTrace) String() string {
return fmt.Sprintf("RayTrace{Var1:%v Var2:%v Var3:%v UserID:%v}", r.Var1, r.Var2, r.Var3, r.UserID)
}
func GetRaytracesFor(id uint) []*RayTrace {
raytraces := make([]*RayTrace, 0)
err := GetDB().Table("ray_traces").Where("user_id = ?", id).Last(&raytraces).Error
if err != nil {
return nil
}
// now we can print anywhere without need to loop each element
fmt.Println(raytraces)
return raytraces
}
More to read:更多阅读:
golang how to print struct value with pointer golang如何用指针打印结构值
https://golang.org/pkg/fmt/#Printf https://golang.org/pkg/fmt/#Printf
https://golang.org/pkg/fmt/#Stringer https://golang.org/pkg/fmt/#Stringer
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.