怎样用循环打印结构体中的字段?

我想用一个循环打印出结构体中的值,例如

package main

import "fmt"
import "reflect"

type person struct {
name string
age  int
}

func main() {
var bb person
bb.name = "xiaym1"
bb.age = 35

//这里该怎样写

}

如果bb是一个切片,又该如何打印出每个结构体中的值?

共 3 个回复


stevewang

Value.NumField()Value.Field()

# 0

stevewang

v := reflect.ValueOf(person{"steve", 30})
count := v.NumField()
for i := 0; i < count; i++ {
    f := v.Field(i)
    switch f.Kind() {
    case reflect.String:
        fmt.Println(f.String())
    case reflect.Int:
        fmt.Println(f.Int())
    }
}
# 1

gogo

package main

import (
    "fmt"
    "reflect"
)

type NotknownType struct {
    s1, s2, s3 string
}

var secret interface{} = NotknownType{"Ada", "Go", "Oberon"}

func main() {
    value := reflect.ValueOf(secret)
    for i := 0; i < value.NumField(); i++ {
        fmt.Printf("Field %d: %v\n", i, value.Field(i))
    }
}
# 2