go chapter 9 - 反射

https://www.cnblogs.com/diegodu/p/5590133.html

// 反射,根据字段名设置值

package entities

import(
    "reflect"
    "fmt"
)

type TestObj struct {
    Id string 
    Name   string    
}

func (r *TestObj) GetTestStructural(a string) (string) {
    return "123-" + a + "-" + r.Id
}

func (o *TestObj) TryStruct(){
    name := "Name"
    value := 123

    element := reflect.ValueOf(o).Elem()
    field := element.FieldByName(name)

    if !field.IsValid() {
        fmt.Printf("No such field: %s in obj\n", name)
        return
    }

    if !field.CanSet() {
        fmt.Printf("Cannot set %s field value\n", name)
        return
    }

    fieldType := field.Type()
    val := reflect.ValueOf(value)
    if fieldType != val.Type() {
        fmt.Printf("Provided value type %s didn't match obj field type %s\n", val.Type(), fieldType)
        return
    }

    field.Set(val)
}

  

func TestS1() {
    r := &entities.TestObj{Name:"tom", Id:"jerry"}
    b := r.GetTestStructural("hehe")
    fmt.Println(b)   //  123-hehe-jerry

    r = &entities.TestObj{}
    r.TryStruct()
    fmt.Println("~~~~", r.Name)
}

  

 

posted @ 2018-08-02 18:55  webglcn  阅读(88)  评论(0编辑  收藏  举报