反射

var x float64 = 3.4

fmt.Println("type:", reflect.TypeOf(x))

type: float64


var x float64 = 3.4

v := reflect.ValueOf(x)

fmt.Println("type:", v.Type())

fmt.Println("kind is float64:", v.Kind() == reflect.Float64)

fmt.Println("value:", v.Float())  //比如.Int().string(),用于返回对应的值

结果为: type: float64

kind is float64: true

value: 3.4


结构的反射操作

下面的示例演示 了如何获取一个结构中所有成员的值:

反射_第1张图片

可以看出,对于结构的反射操作并没有根本上的不同,只是用了Field()方法来按索引获取 对应的成员。当然,在试图修改成员的值时,也需要注意可赋值属性。

注:

Elem返回接口v包含的值或指针v指向的值。 如果v的种类不是接口或Ptr,它会引起恐慌。 如果v为nil,则返回零值。


栗:(只看用法)

func getFieldValue(value reflect.Value) interface{} {
	var fieldValue interface{}
	if value.Kind() == reflect.Ptr {
		value = value.Elem()
	}
	kind := value.Kind()
	ty := value.Type()
	switch {
	case kind >= reflect.Int && kind <= reflect.Int64:
		fieldValue = value.Int()
	case kind >= reflect.Float32 && kind <= reflect.Float64:
		fieldValue = value.Float()
	case ty == reflect.TypeOf(time.Time{}):
		fieldValue = value.Interface().(time.Time).Unix()
	case kind == reflect.Array:
		fieldValue = value.Bytes()
	case kind == reflect.Slice:
		fieldValue = value.Bytes()
	default:
		fieldValue = value.Interface()
	}
	return fieldValue
}
func WeaklyTypedHook(
	f reflect.Type,
	t reflect.Type,
	data interface{}) (interface{}, error) {
	dataVal := reflect.ValueOf(data)
	switch t.Kind() {
	case reflect.String:
		switch f.Kind() {
		case reflect.Bool:
			if dataVal.Bool() {
				return "1", nil
			}
			return "0", nil
		case reflect.Float32:
			return strconv.FormatFloat(dataVal.Float(), 'f', -1, 64), nil
		case reflect.Int:
			return strconv.FormatInt(dataVal.Int(), 10), nil
		case reflect.Slice:
			dataType := dataVal.Type()
			elemKind := dataType.Elem().Kind()
			if elemKind == reflect.Uint8 {
				return string(dataVal.Interface().([]uint8)), nil
			}
		case reflect.Uint:
			return strconv.FormatUint(dataVal.Uint(), 10), nil
		}

	}
	switch t {
	case reflect.TypeOf(time.Time{}):
		switch f.Kind() {
		case reflect.String:
			return time.Parse("2006-01-02 15:04:05", dataVal.String())
		case reflect.Int, reflect.Int32, reflect.Int64:
			return time.Unix(dataVal.Int(), 0), nil
		}

	}

	return data, nil
}

 

你可能感兴趣的:(go)