Skip to content

Instantly share code, notes, and snippets.

@Code-Hex
Last active August 10, 2018 13:17
Show Gist options
  • Select an option

  • Save Code-Hex/71d48d14b7fec37527d3202689dd8d7f to your computer and use it in GitHub Desktop.

Select an option

Save Code-Hex/71d48d14b7fec37527d3202689dd8d7f to your computer and use it in GitHub Desktop.
Go, inteface type validation (channel and pointer of empty struct)
package fetcher
import (
"errors"
"fmt"
"reflect"
)
func validateEmptyStructValue(v reflect.Value) error {
if !v.IsValid() || v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct {
return errors.New("must pass a empty struct pointer")
}
if !isZero(v) {
return errors.New("must pass a empty struct pointer, you passed containing values")
}
return nil
}
func validateSendChannel(chrv reflect.Value) error {
if !chrv.IsValid() || chrv.Kind() != reflect.Chan {
typ := "nil"
if chrv.IsValid() {
typ = chrv.Type().String()
}
return fmt.Errorf(`must pass a channel which is send direction (got "%s")`, typ)
}
if (chrv.Type().ChanDir() & reflect.SendDir) == 0 {
return errors.New(`must pass a channel which is send direction`)
}
return nil
}
func isZero(v reflect.Value) bool {
switch v.Kind() {
case reflect.Bool:
return v.Bool() == false
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32,
reflect.Uint64, reflect.Uintptr:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Complex64, reflect.Complex128:
return v.Complex() == 0
case reflect.Ptr, reflect.Interface:
return !v.IsNil()
case reflect.Array:
for i := 0; i < v.Len(); i++ {
if !isZero(v.Index(i)) {
return false
}
}
return true
case reflect.Slice, reflect.String, reflect.Map:
return v.Len() == 0
case reflect.Struct:
for i, n := 0, v.NumField(); i < n; i++ {
if !isZero(v.Field(i)) {
return false
}
}
return true
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment