亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

Go
手掌心 2023-05-04 16:51:39
我正在尋找一個 lib 或片段,它允許(漂亮地)打印結構實例的內容而不是它的結構。下面是一些代碼和預期的輸出:package mainimport "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但我不想漂亮地打印數據,我只需要結構的定義。
查看完整描述

2 回答

?
搖曳的薔薇

TA貢獻1793條經驗 獲得超6個贊

這樣的事情行得通嗎?可能需要根據您的特定結構和用例進行一些調整(是否要打印接口{},其中值實際上是一個結構等)


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 鏈接:https://play.golang.org/p/IN8-fCOe0OS


查看完整回答
反對 回復 2023-05-04
?
楊魅力

TA貢獻1811條經驗 獲得超6個贊

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


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

}


查看完整回答
反對 回復 2023-05-04
  • 2 回答
  • 0 關注
  • 172 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號