Struct 如何在控制台中打印结构变量?

Struct 如何在控制台中打印结构变量?,struct,go,Struct,Go,如何(在控制台中)在Golang中打印此结构的Id、Title、Name等 type Project struct { Id int64 `json:"project_id"` Title string `json:"title"` Name string `json:"name"` Data Data `json:"data"` Commits Commits `json:"commits"` } 要打印结构中字

如何(在控制台中)在Golang中打印此结构的
Id
Title
Name

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\n", yourProject)
从:

打印结构时,加号标志(
%+v
)会添加字段名

假设您有一个Project实例(在“
yourProject
”中)

本文将详细介绍如何从JSON结构中检索值


这提供了另一种技术:

type Response2 struct {
  Page   int      `json:"page"`
  Fruits []string `json:"fruits"`
}

res2D := &Response2{
    Page:   1,
    Fruits: []string{"apple", "peach", "pear"}}
res2B, _ := json.Marshal(res2D)
fmt.Println(string(res2B))
这将打印:

{"page":1,"fruits":["apple","peach","pear"]}

如果没有任何实例,则需要显示给定结构的字段名称

T型结构{
整数
B弦
}
t:=t{23,“skidoo”}
s:=reflect.ValueOf(&t).Elem()
typeOfT:=s.Type()
对于i:=0;i
我想推荐,根据他们的github,“为Go数据结构实现了一个deep pretty打印机,以帮助调试”

用法示例:

package main

import (
    "github.com/davecgh/go-spew/spew"
)

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

func main() {

    o := Project{Name: "hello", Title: "world"}
    spew.Dump(o)
}
输出:

(main.Project) {
 Id: (int64) 0,
 Title: (string) (len=5) "world",
 Name: (string) (len=5) "hello",
 Data: (string) "",
 Commits: (string) ""
}
还有一个函数,它处理指针递归和许多字符串和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)}
访问查看完整的代码。在这里,您还可以找到一个在线终端的链接,其中可以运行完整的代码,程序表示如何提取结构信息(字段名称、类型和值)。下面是只打印字段名的程序段

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
*/
主程序包
输入“fmt”
导入“反映”
func main(){
类型书结构{
Id int
名称字符串
标题字符串
}
book:=book{1,“让我们来C”,“在实践中享受编程”}
e:=reflect.ValueOf(&book).Elem()
对于i:=0;i
我认为如果您想要某种
结构的格式化输出,最好实现一个自定义stringer

比如说

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

快乐编码;)

另一种方法是,创建一个名为
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())
}

不使用外部库,且每个字段后面都有新行:

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

从他们的自述:

type Person struct {
  Name   string
  Age    int
  Parent *Person
}

litter.Dump(Person{
  Name:   "Bob",
  Age:    20,
  Parent: &Person{
    Name: "Jane",
    Age:  50,
  },
})
Sdump
在测试中非常方便:

func TestSearch(t *testing.T) {
  result := DoSearch()

  actual := litterOpts.Sdump(result)
  expected, err := ioutil.ReadFile("testdata.txt")
  if err != nil {
    // First run, write test data since it doesn't exist
        if !os.IsNotExist(err) {
      t.Error(err)
    }
    ioutil.Write("testdata.txt", actual, 0644)
    actual = expected
  }
  if expected != actual {
    t.Errorf("Expected %s, got %s", expected, actual)
  }
}

我的目标是使用
json.marshallindent
——奇怪的是,这不是建议的,因为它是最简单的。例如:

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

没有外部DEP,输出格式很好。

当您有更复杂的结构时,您可能需要在打印前转换为JSON:

// Convert structs to JSON.
data, err := json.Marshal(myComplexStruct)
fmt.Printf("%s\n", data)
来源:

我建议使用。因为你可以很容易地打印任何结构

  • 安装库

  • 现在在代码中这样做

    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.
    
    }
    
    //In commons package
    const STRUCTURE_DATA_FMT = "%+v"
    
    //In your code everywhere
    fmt.Println(commons.STRUCTURE_DATA_FMT, structure variable)
    
    此外,您还可以通过此库等获取组件之间的差异。你们也可以在这里看看图书馆

    更好的方法是在名为“commons”(可能)的包中为字符串“%+v”创建一个全局常量,并在代码中的任何地方使用它

    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.
    
    }
    
    //In commons package
    const STRUCTURE_DATA_FMT = "%+v"
    
    //In your code everywhere
    fmt.Println(commons.STRUCTURE_DATA_FMT, structure variable)
    

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

    为了使用它,除了
    fmt
    encoding/json
    之外,您不需要任何额外的包,只需要创建的结构的引用、指针或文本

    要使用它,只需在main或您所在的任何包中初始化结构,并将其传递到
    PrettyPrint()

    它的输出将是

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

    玩转代码

    这些包中的大多数都依赖于reflect包来实现这些功能

    Sprintf()正在使用标准库的->func(p*pp)printArg(arg接口{},动词符文)

    转到第638行->

    反思:

    示例代码:

    这是打印细节的基本方法,非常简单
        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    string  `json:"data"`
        Commits string  `json:"commits"`
    }
    
    func main() {
        p := Project{
        1,
        "First",
        "Ankit",
        "your data",
        "Commit message",
        }
        fmt.Println(p)
    }
    

    对于学习,您可以从这里获得帮助:

    也许这不应该应用于生产请求,但如果您处于调试模式,我建议您遵循以下方法

    marshalledText, _ := json.MarshalIndent(inputStruct, "", " ")
    fmt.Println(string(marshalledText))
    
    这将导致以json格式格式化数据,从而提高可读性。

    package main

    import "fmt"
    
    type Project struct {
        Id int64 `json:"id"`
        Title string `json:"title"`
    }
    
    func (p Project) String() string {
        return fmt.Sprintf("{Id:%d, Title:%s, Name:%s}", p.Id, p.Title)
    }
    
    func main() {
        var instance Project
        Instance = Project{Id: 100, Title: "Print Struct"}
        fmt.Printf("%v\n", Instance)
    }
    

    要将结构打印为JSON,请执行以下操作:

    fmt.Printf("%#v\n", yourProject)
    
    也可以使用(如上所述):


    但是第二个选项打印不带“”的字符串值,因此更难读取。

    如果要在控制台中打印任何类型的结构,在Go中有一个名为Stringer的接口:

    type Stringer interface {
        String() string
    }
    
    实施守则如下:

    type Project struct {
        Id      int64   `json:"project_id"`
        Title   string  `json:"title"`
        Name    string  `json:"name"`
        Data    Data    `json:"data"`
        Commits Commits `json:"commits"`
    }
    func (p Project) String() string {
        return fmt.Sprintf("ID:%s,Title:%s",p.Id,p.Title)
    }
    
    您可以选择所需的任何打印策略,只需键入:

    p := &Project{Id:1,Title:"title"}
    fmt.Println(p)
    

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

    log.Infof("Information %+v", structure)
    
    注意::这不适用于log.Info或log.Debug。在这种情况下,“%v”将被打印,结构的所有值都将被打印,而不打印键/变量名

    fmt.Printf(“%+v\n”,结构名称)


    这可用于打印终端或控制台中的结构,以便调试?试试
    fmt.Println
    。我真的很想用spew谢谢你的回答,但还有一件事。我的JSON文件与API相关。。。因此,我不想设置Id或名称,我只想通过API将其打印到控制台中。我该怎么做?@fnr如果你有一个JSON文档,你需要先解组它,然后才能打印它的字段。向上投票!我的一个抱怨是%+v命令没有很好地打印它!我仍然对这一行的效率感到满意。需要为json编组技术导入“encoding/json”,请注意.Printf(“%+v\n”)也可以与“log”包一起使用您可以添加go spew所具有的解引用功能。全部
    import "fmt"
    
    type Project struct {
        Id int64 `json:"id"`
        Title string `json:"title"`
    }
    
    func (p Project) String() string {
        return fmt.Sprintf("{Id:%d, Title:%s, Name:%s}", p.Id, p.Title)
    }
    
    func main() {
        var instance Project
        Instance = Project{Id: 100, Title: "Print Struct"}
        fmt.Printf("%v\n", Instance)
    }
    
    fmt.Printf("%#v\n", yourProject)
    
    fmt.Printf("%+v\n", yourProject)
    
    type Stringer interface {
        String() string
    }
    
    type Project struct {
        Id      int64   `json:"project_id"`
        Title   string  `json:"title"`
        Name    string  `json:"name"`
        Data    Data    `json:"data"`
        Commits Commits `json:"commits"`
    }
    func (p Project) String() string {
        return fmt.Sprintf("ID:%s,Title:%s",p.Id,p.Title)
    }
    
    p := &Project{Id:1,Title:"title"}
    fmt.Println(p)
    
    log.Infof("Information %+v", structure)