How to get zero value of a field type

后端 未结 3 684
孤街浪徒
孤街浪徒 2021-02-04 04:47

I have a struct containing many fields - I\'ve figured out how to extract the field name, value, and tag information using reflection. What I also want to do is to determine if

3条回答
  •  一整个雨季
    2021-02-04 05:38

    You can switch on the Kind() of the Value and use the appropriate accessor (many fewer kinds than types). Something like:

    switch valueField.Kind() {
    case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
        if valueField.Int() == 0 {...}
    case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
        if valueField.Uint() == 0 {...}
    case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
        if valueField.IsNil() {...}
    //add more cases for Float, Bool, String, etc (and anything else listed http://golang.org/pkg/reflect/#Kind )
    }
    

    You could also get a zeroed instance of a value by using reflect.Zero(valueField.Type()) but it is not safe to compare that with valueField since some types (such as slices and maps) do not support equality and would panic.

提交回复
热议问题