Created
March 1, 2018 03:55
-
-
Save tsilvers/c467e51f387ae24ffde5ff21fc14b484 to your computer and use it in GitHub Desktop.
Golang walk through nested structures with formatted, indented output
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"reflect" | |
"strings" | |
) | |
type S1 struct { | |
A1 int | |
B1 string | |
S2 | |
} | |
type S2 struct { | |
A2 int64 | |
S3 | |
B2 complex64 | |
} | |
type S3 struct { | |
A3 string | |
b3 bool | |
C3 float64 | |
} | |
func main() { | |
s3 := S3{"Third", true, 3.1415926535} | |
s2 := S2{4123456789, s3, -2 + 3i} | |
s1 := S1{7, "first", s2} | |
walkNestedStruct(s1, 0) | |
} | |
func walkNestedStruct(ns interface{}, level int) { | |
nsVal := reflect.ValueOf(ns) | |
nsType := nsVal.Type() | |
for i := 0; i < nsVal.NumField(); i++ { | |
f := nsVal.Field(i) | |
// Skip unexported fields | |
if !f.CanInterface() { | |
continue | |
} | |
fmt.Printf("%s%s", strings.Repeat(" ", level), nsType.Field(i).Name) | |
if f.Kind() == reflect.Struct { | |
fmt.Println(" {") | |
walkNestedStruct(f.Interface(), level+4) | |
fmt.Printf("%s}\n", strings.Repeat(" ", level)) | |
} else { | |
fmt.Printf(" %s = %v\n", f.Type(), f.Interface()) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment