我如何打印(到控制台)的Id,标题,名称等,这个结构在Golang?
type Project struct {
Id int64 `json:"project_id"`
Title string `json:"title"`
Name string `json:"name"`
Data Data `json:"data"`
Commits Commits `json:"commits"`
}
我如何打印(到控制台)的Id,标题,名称等,这个结构在Golang?
type Project struct {
Id int64 `json:"project_id"`
Title string `json:"title"`
Name string `json:"name"`
Data Data `json:"data"`
Commits Commits `json:"commits"`
}
当前回答
p = Project{...}
fmt.Printf("%+v", p)
fmt.Printf("%#v", p) //with type
其他回答
不使用外部库,每个字段后加新行:
log.Println(
strings.Replace(
fmt.Sprintf("%#v", post), ", ", "\n", -1))
这些包中的大多数都依赖于reflect包来实现这些功能。
fmt.Sprintf()正在使用-> func (p *pp) printArg(参数接口{},动词符文)的标准库
转到第638行-> https://golang.org/src/fmt/print.go
反射:
https://golang.org/pkg/reflect/
示例代码:
https://github.com/donutloop/toolkit/blob/master/debugutil/prettysprint.go
我认为如果想要某种格式化的结构输出,最好实现自定义字符串
例如
package main
import "fmt"
type Project struct {
Id int64 `json:"project_id"`
Title string `json:"title"`
Name string `json:"name"`
}
func (p Project) String() string {
return fmt.Sprintf("{Id:%d, Title:%s, Name:%s}", p.Id, p.Title, p.Name)
}
func main() {
o := Project{Id: 4, Name: "hello", Title: "world"}
fmt.Printf("%+v\n", o)
}
使用包fmt输出非常方便:
fmt.Printf("%+v \n", yourProject)
如果你想看到完整的sturct类型,你可以使用# replace +:
fmt.Printf("%#v \n", yourProject)
另一种方法是,创建一个名为toString的func,它接受struct,格式化 如你所愿。
import (
"fmt"
)
type T struct {
x, y string
}
func (r T) toString() string {
return "Formate as u need :" + r.x + r.y
}
func main() {
r1 := T{"csa", "ac"}
fmt.Println("toStringed : ", r1.toString())
}