我如何打印(到控制台)的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"`
}

当前回答

使用包fmt输出非常方便:

fmt.Printf("%+v \n", yourProject)

如果你想看到完整的sturct类型,你可以使用# replace +:

fmt.Printf("%#v \n", yourProject) 

其他回答

p = Project{...}
fmt.Printf("%+v", p)
fmt.Printf("%#v", p) //with type

使用包fmt输出非常方便:

fmt.Printf("%+v \n", yourProject)

如果你想看到完整的sturct类型,你可以使用# replace +:

fmt.Printf("%#v \n", yourProject) 

我认为如果想要某种格式化的结构输出,最好实现自定义字符串

例如

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

我认为应该使用json。MarshalIndent——令人惊讶的是没有建议这样做,因为它是最直接的。例如:

func prettyPrint(i interface{}) string {
    s, _ := json.MarshalIndent(i, "", "\t")
    return string(s)
}

没有外部deps,结果输出格式很好。

不使用外部库,每个字段后加新行:

log.Println(
            strings.Replace(
                fmt.Sprintf("%#v", post), ", ", "\n", -1))