我如何打印(到控制台)的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.Printf("%+v\n", project)

这是打印细节的基本方法

    type Response struct {
        UserId int    `json:"userId"`
        Id     int    `json:"id"`
        Title  string `json:"title"`
        Body   string `json:"body"`
    }

    func PostsGet() gin.HandlerFunc {
        return func(c *gin.Context) {
            xs, err := http.Get("https://jsonplaceholder.typicode.com/posts")
            if err != nil {
                log.Println("The HTTP request failed with error: ", err)
            }
            data, _ := ioutil.ReadAll(xs`enter code here`.Body)


            // this will print the struct in console            
            fmt.Println(string(data))


            // this is to send as response for the API
            bytes := []byte(string(data))
            var res []Response
            json.Unmarshal(bytes, &res)

            c.JSON(http.StatusOK, res)
        }
    }

我推荐使用Pretty Printer Library。这样你可以很容易地打印任何结构体。

安装库 https://github.com/kr/pretty

or

go get github.com/kr/pretty

现在在代码中这样做

package main

import (
fmt
github.com/kr/pretty
)

func main(){

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.Printf("%# v", pretty.Formatter(Project)) //It will print all struct details

fmt.Printf("%# v", pretty.Formatter(Project.Id)) //It will print component one by one.

}

此外,您还可以通过这个库获取组件之间的差异等等。你也可以在这里查看图书馆文档。

使用包fmt输出非常方便:

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

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

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