簡體   English   中英

從Go中的實例打印結構定義

[英]Print struct definition from an instance in Go

我正在尋找一個lib或片段,允許(漂亮地)打印結構實例的內容,但不是它的結構。 下面是一些代碼和預期的輸出:

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

會打印(這個或類似的):

Foo struct {
    Bar string
    Other int
}   

請注意,我知道github.com/davecgh/go-spew/spew但我不想重新打印數據,我只需要結構的定義。

會這樣的嗎? 可能需要一些調整,具體取決於您的特定結構和用例(是否要打印接口{},其中值實際上是一個結構,等等)

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\n", prefix, typeOfT.Field(i).Name, typeOfT.Field(i).Type)
        switch f.Type().Kind() {
        case reflect.Struct, reflect.Ptr:
            fmt.Printf("%s{\n", prefix)
            printStruct(f.Interface(), prefix+"\t")
            fmt.Printf("%s}\n", prefix)

        }
    }
}

然后,對於這個結構:

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",
    },
}

你得到:

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

除了使用反射,我看不到其他選擇

func Sprint(v interface{}) string {

    t := reflect.Indirect(reflect.ValueOf(v)).Type()

    fieldFmt := ""

    for i := 0; i < t.NumField(); i++ {
        field := t.Field(i)
        fieldFmt += "\t" + field.Name + " " + field.Type.Name() + "\n"
    }

    return "type " + t.Name() + " struct {\n" + fieldFmt + "}"
}

請注意,此函數沒有驗證/檢查,可能會對非結構輸入發生混亂。

編輯:去游樂場: https//play.golang.org/p/5RiAt86Wj9F

哪個輸出:

type Foo struct {
    Bar string
    Other int
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM