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

其他回答

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

我认为应该使用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))

如果您想写入日志文件,就像我之前搜索的那样。那么你应该使用:

log.Infof("Information %+v", structure)

注意::这将不适用于log。Info或log.Debug。在本例中,将打印“%v”,并且打印结构的所有值,而不打印键/变量名。

或者,尝试使用这个函数PrettyPrint()

// print the contents of the obj
func PrettyPrint(data interface{}) {
    var p []byte
    //    var err := error
    p, err := json.MarshalIndent(data, "", "\t")
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("%s \n", p)
}

为了使用这个,除了fmt和encoding/json之外,你不需要任何额外的包,只需要一个引用、指针或你所创建的结构的文字。

为了使用你的结构,初始化它在main或任何包中,并将它传递给PrettyPrint()。

type Prefix struct {
    Network string
    Mask    int
}

func valueStruct() {
    // struct as a value
    var nw Prefix
    nw.Network = "10.1.1.0"
    nw.Mask = 24
    fmt.Println("### struct as a pointer ###")
    PrettyPrint(&nw)
}

它的输出是

### struct as a pointer ###
{
    "Network": "10.1.1.0",
    "Mask": 24
} 

摆弄一下这里的代码。