通过反射判断某类型是否为空

package main

import (
    "fmt"
    "reflect"
)

const (
    defaultInt    = 0
    defaultString = ""
)

func NotNullCheck(v interface{}) error {
    k := reflect.TypeOf(v).Kind()
    switch k {
    // leaf
    case reflect.Int64, reflect.Int32:
        {
            if reflect.ValueOf(v).Interface().(int64) == defaultInt {
                return fmt.Errorf("empty Int")
            }
        }
    case reflect.String:
        {
            if reflect.ValueOf(v).Interface().(string) == defaultString {
                return fmt.Errorf("empty string")
            }
        }
    // not leaf
    case reflect.Ptr:
        {
            if err := handlePtr(v); err != nil {
                return err
            }
        }
    case reflect.Struct:
        {
            if err := handleStruct(v); err != nil {
                return err
            }
        }
    }
    return nil
}

func handlePtr(v interface{}) error {
    if reflect.ValueOf(v).IsNil() {
        return fmt.Errorf("nil ptr")
    }
    if err := NotNullCheck(reflect.ValueOf(v).Elem().Interface()); err != nil {
        return err
    }
    return nil
}

func handleStruct(v interface{}) error {
    structType := reflect.TypeOf(v)
    for i := 0; i < structType.NumField(); i++ { // every member of struct
        fieldType := structType.Field(i)
        if err := NotNullCheck(reflect.ValueOf(v).FieldByName(fieldType.Name).Interface()); err != nil {
            return err
        }
    }
    return nil
}

type Student struct {
    Name string
    Sex  int64
}

func main() {
    stu := &Student{
        Name: "aaa",
        Sex:  0,
    }
    fmt.Println(NotNullCheck(stu))
    stu = nil
    fmt.Println(NotNullCheck(stu))

    // typeofb := reflect.TypeOf(b)
    // fmt.Println("type of b:", typeofb) //int*

    // newb := reflect.ValueOf(b).Interface()
    // fmt.Println(newb) // 0xc0000180b0
    // elem := reflect.ValueOf(b).Elem()
    // fmt.Println(elem.Type())
    // fmt.Println(elem.Interface())
    // fmt.Println(reflect.Zero(reflect.TypeOf(elem.Interface())))
}

你可能感兴趣的:(通过反射判断某类型是否为空)