ZhangZhihui's Blog  

 

 

package main

import (
    "fmt"
    "reflect"
)

type Secret struct {
    Username string
    Password string
}

type Record struct {
    Field1 string
    Field2 float64
    Field3 Secret
}

func main() {
    A := Record{"String value", -12.123, Secret{"Mihalis", "Tsoukalos"}}
    r := reflect.ValueOf(A)
    fmt.Println("String value:", r.String())

    iType := r.Type()
    fmt.Printf("i Type: %s\n", iType)
    fmt.Printf("The %d fields of %s are\n", r.NumField(), iType)
    for i := 0; i < r.NumField(); i++ {
        fmt.Printf("\t%s ", iType.Field(i).Name)
        fmt.Printf("\twith type: %s ", r.Field(i).Type())
        fmt.Printf("\tand value _%v_\n", r.Field(i).Interface())
        // Check whether there are other structures embedded in Record
        // k := reflect.TypeOf(r.Field(i).Interface()).Kind()
        k := r.Field(i).Kind()
        // Need to convert it to string in order to compare it
        if k.String() == "struct" {
            fmt.Println(r.Field(i).Type())
        }
        // Same as before but using the internal value
        if k == reflect.Struct {
            fmt.Println(r.Field(i).Type())
        }
    }
}

 

zzh@ZZHPC:/zdata/Github/ztest$ go run main.go
String value: <main.Record Value>
i Type: main.Record
The 3 fields of main.Record are
        Field1  with type: string       and value _String value_
        Field2  with type: float64      and value _-12.123_
        Field3  with type: main.Secret  and value _{Mihalis Tsoukalos}_
main.Secret
main.Secret
zzh@ZZHPC:/zdata/Github/ztest$ go run main.go
String value: <main.Record Value>
i Type: main.Record
The 3 fields of main.Record are
        Field1  with type: string       and value _String value_
        Field2  with type: float64      and value _-12.123_
        Field3  with type: main.Secret  and value _{Mihalis Tsoukalos}_
main.Secret
main.Secret

 

 

package main

import (
    "fmt"
    "reflect"
)

type T struct {
    F1 int
    F2 string
    F3 float64
}

func main() {
    A := T{1, "F2", 3.0}
    fmt.Println("A:", A)
    r := reflect.ValueOf(&A).Elem()
    fmt.Println("String value:", r.String())
    typeOfA := r.Type()
    for i := 0; i < r.NumField(); i++ {
        f := r.Field(i)
        tOfA := typeOfA.Field(i).Name
        fmt.Printf("%d: %s %s = %v\n", i, tOfA, f.Type(), f.Interface())
        k := f.Kind()
        if k == reflect.Int {
            r.Field(i).SetInt(-100)
        } else if k == reflect.String {
            r.Field(i).SetString("Changed!")
        }
    }

    fmt.Println("A:", A)
}

 

zzh@ZZHPC:/zdata/Github/ztest$ go run main.go
A: {1 F2 3}
String value: <main.T Value>
0: F1 int = 1
1: F2 string = F2
2: F3 float64 = 3
A: {-100 Changed! 3}

 

 

posted on 2024-06-11 17:07  ZhangZhihuiAAA  阅读(4)  评论(0编辑  收藏  举报