How to cast interface{} to a given interface?

Sure, if you’re going to cast a type T to Validator, then there needs to be a Validate function defined on T. One defined on *T will not do. Just like a Validate function defined on some other type U will not do.

Possibly you could do something like:
func ValidateValue(value reflect.Value) error {
if validator, ok := value.Interface().(Validator); ok { …; return }
t := reflect.New(value.Type()) // of type *T
t.Elem().Set(value) // copy value to *T
if validator, ok := t.Interface().(Validator); ok { …; return }
}

Note that this copies the underlying object, so any modifications done by the Validate pointer method will get silently ignored.

3 Likes