dplo59755 2018-10-29 07:03
浏览 14
已采纳

从Go中的实例打印结构定义

I am looking for a lib or snippet that allows to (pretty) print not the content of a struct instance but its structure. Heres a some code and the expected output:

package main

import "fantastic/structpp"

type Foo struct {
    Bar string
    Other int
}

func main() {
    i := Foo{Bar: "This", Other: 1}
    str := structpp.Sprint{i}
    fmt.Println(str)
}

would print (this or similar):

Foo struct {
    Bar string
    Other int
}   

Note that I am aware of github.com/davecgh/go-spew/spew but I don't want to prettyprint the data, I only need the definition of the struct.

  • 写回答

2条回答 默认 最新

  • doucong7963 2018-10-29 08:03
    关注

    Would something like this work? Might need some adjusting depending on your specific struct and use case (whether you want to print interfaces{} where the value is actually a struct, etc.)

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    func printStruct(t interface{}, prefix string) {
        s := reflect.Indirect(reflect.ValueOf(t))
        typeOfT := s.Type()
    
        for i := 0; i < s.NumField(); i++ {
            f := s.Field(i)
    
            fmt.Printf("%s%s %s
    ", prefix, typeOfT.Field(i).Name, typeOfT.Field(i).Type)
            switch f.Type().Kind() {
            case reflect.Struct, reflect.Ptr:
                fmt.Printf("%s{
    ", prefix)
                printStruct(f.Interface(), prefix+"\t")
                fmt.Printf("%s}
    ", prefix)
    
            }
        }
    }
    

    Then, for this struct:

    type C struct {
        D string
    }
    
    type T struct {
        A int
        B string
        C *C
        E interface{}
        F map[string]int
    }
    
    t := T{
        A: 23,
        B: "hello_world",
        C: &C{
            D: "pointer",
        },
        E: &C{
            D: "interface",
        },
    }
    

    You get:

    A int
    B string
    C *main.C
    {
        D string
    }
    E interface {}
    F map[string]int
    

    Go Playground Link: https://play.golang.org/p/IN8-fCOe0OS

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路