登录
首页 >  Golang >  Go问答

打印 Go 中实例的结构定义

来源:stackoverflow

时间:2024-03-11 15:42:27 295浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《打印 Go 中实例的结构定义》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

我正在寻找一个库或片段,它允许(漂亮地)打印结构实例的内容而不是其结构。这是一些代码和预期输出:

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 演示链接: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
}

到这里,我们也就讲完了《打印 Go 中实例的结构定义》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>