Go:万能程序

By kcersing , 11 四月, 2020

package ce27
import (
    "errors"
    "fmt"
    "reflect"
    "testing"
)
//DeepEqual
func TestDeepEqual(t *testing.T) {
    /*比较切片和map*/
    //map
    a := map[int]string{1: "one", 2: "two", 3: "three"}
    b := map[int]string{1: "one", 2: "two", 3: "three"}
    fmt.Println(reflect.DeepEqual(a, b))
    fmt.Println("-----------------------------")
    //切片
    s1 := []int{1, 2, 3}
    s2 := []int{1, 2, 3}
    s3 := []int{1, 2, 3}
    t.Log("s1==s2?", reflect.DeepEqual(s1, s2))
    t.Log("s1==s3?", reflect.DeepEqual(s1, s3))
    fmt.Println("-----------------------------")
    /* End */
    c1 := Customer{"1", "Mike", 40}
    c2 := Customer{"1", "Mike", 40}
    fmt.Println(c1, c2)
}
type Employee struct {
    EmployeeId string
    Name       string
    Age        int
}
func (e *Employee) UpdateAge(newVal int) {
    e.Age = newVal
}
type Customer struct {
    CookieId string
    Name     string
    Age      int
}
func fillBySettings(st interface{}, settings map[string]interface{}) error {
    if reflect.TypeOf(st).Kind() != reflect.Ptr {
        //Elem() 获取指针指向的值
        if reflect.ValueOf(st).Elem().Kind() != reflect.Struct {
            return errors.New("the first param should be a pointer to the struct type ")
        }
    }
    if settings == nil {
        return errors.New("Settings in nil.")
    }
    var (
        field reflect.StructField
        ok    bool
    )
    for k, v := range settings {
        //检查类型中是否存在 field
        if field, ok = (reflect.ValueOf(st)).Elem().Type().FieldByName(k); !ok {
            continue
        }
        //field类型是否一致
        if field.Type == reflect.TypeOf(v) {
            vstr := reflect.ValueOf(st)
            //获取指针指向的结构
            vstr = vstr.Elem()
            //填充
            vstr.FieldByName(k).Set(reflect.ValueOf(v))
        }
    }
    return nil
}
func TestFillNameAndAge(t *testing.T) {
    settings := map[string]interface{}{"Name": "Mike", "Age": 30}
    e := Employee{}
    if err := fillBySettings(&e, settings); err != nil {
        t.Fatal(err)
    }
    t.Log(e)
    c := new(Customer)
    if err := fillBySettings(c, settings); err != nil {
        t.Fatal(err)
    }
    t.Log(*c)
}


标签