【1个月读懂filebeat源码】第28天
2021-04-11 13:46:21 By

  • 10.2 Unit() 方法可以返回无符号整型的基础类型(unit64),即能表示范围最大的类型。而 Type() 返回静态类型,可能是用户定义的(type MyInt unit8,则返回 MyInt)。
package main

import (
    "fmt"
    "reflect"
)

func main() {
    var x uint8 = 'x'
    v := reflect.ValueOf(x)
    fmt.Println("type:", v.Type())                            // uint8.
    fmt.Println("kind is uint8: ", v.Kind() == reflect.Uint8) // true.
    x = uint8(v.Uint())                                       // v.Uint returns a uint64.
}
  • 10.2 反射可以将反射类型对象转换为接口类型对象,使用 Interface 方法恢复其接口类型的值,如下转换为 interface 对象后,进行断言
y := v.Interface().(float64) // y will have type float64.
fmt.Println(y)
  • 10.4 反射中 TypeOf().Name() 为类型名称,如:整型、布尔、浮点、字符串,也包括 type 定义的类型名称(type MyInt int 就是 MyInf,type A struct{} 就是 A),TypeOf().Kind() 为类型的种类,如:整型、布尔、浮点、字符串、结构体、指针、Map 等
  • 10.14 如果一个 func 有多个同类型的参数,怎么在 Invoke 区分呢,应该是无法区分,并且会发生后者覆盖前者
func (inj *injector) Invoke(f interface{}) ([]reflect.Value, error) {
    t := reflect.TypeOf(f)

    var in = make([]reflect.Value, t.NumIn()) //Panic if t is not kind of Func
    for i := 0; i < t.NumIn(); i++ {
        argType := t.In(i)
        val := inj.Get(argType)
        if !val.IsValid() {
            return nil, fmt.Errorf("Value not found for type %v", argType)
        }
        in[i] = val
    }
    return reflect.ValueOf(f).Call(in), nil
}
  • 10.14 struct 的注入字段必须是可导出(大写开头),并且次字段的 tag 是 inject
func (inj *injector) Apply(val interface{}) error {
    v := reflect.ValueOf(val)
    for v.Kind() == reflect.Ptr {
        v = v.Elem()
    }
    if v.Kind() != reflect.Struct {
        return nil
    }
    t := v.Type()
    for i := 0; i < v.NumField(); i++ {
        f := v.Field(i)
        structField := t.Field(i)
        if f.CanSet() && structField.Tag == "inject" {
            ft := f.Type()
            v := inj.Get(ft)
            if !v.IsValid() {
                return fmt.Errorf("Value not found for type %v", ft)
            }
            f.Set(v)
        }
    }
    return nil
}


© 2016-2021 taluo.ren 版权所有 ICP证:蜀ICP备15023822号-2