Home > other >  Ask: how to traverse anything with a combination of all the members of the structure field
Ask: how to traverse anything with a combination of all the members of the structure field

Time:10-10

For example:
Type A struct {
A1 int
}
Type B struct {
A
B1 int
B2 float32
}
Type C struct {
B
C string
}

Traversing C structure in all fields, output field name, type, value
Using reflection for combination don't know how to do

CodePudding user response:

For example

Func main () {
C: c={}
PrintAll (c)
}

Func PrintAll (obj interface) {} {
E:=reflect the ValueOf (obj)
Var v interface {}
For I:=0; i Name:=e. ype (). The Field (I). The name
Kind:=e.F ield (I). The Type () kind ()
The switch kind {
Case reflect. Struct:
V=e.F ield (I). The Interface ()
PrintAll (v)//if the structure is the recursive
Case reflect. String:
V=e.F ield (I). The String ()
Case reflect. Int, reflect Int16, reflect the Int64, reflect, Int8:
V=e.F ield (I). The Int ()
Case reflect Float32, reflect. Float64:
V=e.F ield (I). The Float ()
Default://ignore other types, can be extended to
V=e.F ield (I). The String ()
}
FMT. Printf (" name=% v, type:=% v, value=https://bbs.csdn.net/topics/%v/n ", name, kind, v)
}
}

CodePudding user response:

Is the c + +, seemingly no Field function
  • Related