MST

星途 面试题库

面试题:Go中反射如何获取结构体字段的类型和值

在Go语言中,给定一个结构体实例,如何使用反射获取其每个字段的类型和对应的值,请写出示例代码。
13.1万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
package main

import (
    "fmt"
    "reflect"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    p := Person{
        Name: "John",
        Age:  30,
    }

    valueOf := reflect.ValueOf(p)
    typeOf := reflect.TypeOf(p)

    for i := 0; i < valueOf.NumField(); i++ {
        fieldValue := valueOf.Field(i).Interface()
        fieldType := typeOf.Field(i).Type
        fmt.Printf("Field %d: Name = %s, Type = %v, Value = %v\n", i+1, typeOf.Field(i).Name, fieldType, fieldValue)
    }
}