go-reflect

Golang
489
0
0
2022-11-08
标签   Golang进阶
func main()  {
    var name string = "抢手"
    nameType := reflect.TypeOf(name)
    nameValue := reflect.ValueOf(name)

    fmt.Println("name type:", nameType)
    fmt.Println("name value", nameValue)
}
type Info struct {
    Name string
    Desc string
}

func (i Info) Detail() {
    fmt.Println("detail info")
}

func main()  {
    i := Info{Name: "malina", Desc:"php"}
    t := reflect.TypeOf(i)
    v := reflect.ValueOf(i)

    fmt.Println(t)
    fmt.Println(v)
    fmt.Println("===")
    for i := 0; i < v.NumField(); i++ {
        key := t.Field(i)
        value := v.Field(i).Interface()
        fmt.Println("key=%s value=%v type=%v\n", key.Name, value, key.Type)
    }

    for i := 0; i < t.NumMethod(); i++ {
        m := t.Method(i)
        fmt.Printf("方法 Name=%s Type=%v\n", m.Name, m.Type)
    }
}
运行结果:
main.Info
{malina php}
===
key=%s value=%v type=%v
 Name malina string
key=%s value=%v type=%v
 Desc php string
方法 Name=Detail Type=func(main.Info)
type Info struct {
    Name string
    Desc string
}

func main()  {
    i := Info{
        Name: "抢手",
        Desc: "php",
    }

    t := reflect.TypeOf(i)

    if k := t.Kind();k ==reflect.Struct{
        fmt.Println("struct type")
    }

    num := 100 
    switch v := reflect.ValueOf(num); v.Kind() {
    case reflect.String:
        fmt.Println("string type")
    case reflect.Int, reflect.Int8, reflect.Int16,reflect.Int32,reflect.Int64:
        fmt.Println("int type")
    default:
        fmt.Println("unhandled kind %s", v.Kind())
    }
}
运行结果:
struct type
int type
type Info struct {
    Name string
    Desc string
}

func main()  {
    i := &Info{Name: "malina", Desc: "php"}
    v := reflect.ValueOf(i)


    // 修改值必须是指针类型 
    if v.Kind()!=reflect.Ptr {
        fmt.Println("不是指针类型")
        return
    }

    v = v.Elem() // 获取指针指向的元素
    name := v.FieldByName("Desc")// 获取目标key的值
    name.SetString("哈哈")
    fmt.Println("修改后数据: %v\n", *i)
}
运行结果:
修改后数据: %v
 {malina 哈哈}
//通过反射调用方法
type Info struct {
    Name string
    Desc string
}

func (i Info) Detail() {
    fmt.Println("detail info")
}

func main()  {
    i := Info{Name: "抢手", Desc: "php"}
    v := reflect.ValueOf(i)
    // 获取方法控制权
    mv := v.MethodByName("Detail")
    mv.Call([]reflect.Value{})// 这里是无调用参数 []reflect.Value{}
}
运行结果:
detail info