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

当前回答

或者,尝试使用这个函数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
} 

摆弄一下这里的代码。

其他回答

这些包中的大多数都依赖于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"
import "reflect"

func main() {
    type Book struct {
        Id    int
        Name  string
        Title string
    }

    book := Book{1, "Let us C", "Enjoy programming with practice"}
    e := reflect.ValueOf(&book).Elem()

    for i := 0; i < e.NumField(); i++ {
        fieldName := e.Type().Field(i).Name
        fmt.Printf("%v\n", fieldName)
    }
}

/*
Id
Name
Title
*/
    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)
        }
    }

一个简单的问题有很多答案。我还不如参加竞选呢。

package main

import "fmt"

type Project struct {
    Id    int64  `json:"project_id"`
    Title string `json:"title"`
    Name  string `json:"name"`
    //Data    Data    `json:"data"`
    //Commits Commits `json:"commits"`
}

var (
    Testy Project
)

func dump_project(foo Project) {
    fmt.Println("== Dump Project Struct ====")
    fmt.Printf("Id: %d\n", foo.Id)
    fmt.Println("Title: ", foo.Title)
    fmt.Printf("Name: %v\n", foo.Name)
}

func main() {
    fmt.Println("hello from go")
    Testy.Id = 3
    Testy.Title = "yo"
    Testy.Name = "my name"
    fmt.Println(Testy)
    dump_project(Testy)
}

输出的各种打印方法

hello from go
{3 yo my name}
== Dump Project Struct ====
Id: 3
Title:  yo
Name: my name

还有go-render,它处理指针递归和字符串和int映射的大量键排序。

安装:

go get github.com/luci/go-render/render

例子:

type customType int
type testStruct struct {
        S string
        V *map[string]int
        I interface{}
}

a := testStruct{
        S: "hello",
        V: &map[string]int{"foo": 0, "bar": 1},
        I: customType(42),
}

fmt.Println("Render test:")
fmt.Printf("fmt.Printf:    %#v\n", a)))
fmt.Printf("render.Render: %s\n", Render(a))

打印:

fmt.Printf:    render.testStruct{S:"hello", V:(*map[string]int)(0x600dd065), I:42}
render.Render: render.testStruct{S:"hello", V:(*map[string]int){"bar":1, "foo":0}, I:render.customType(42)}