For example I defined the following interface:
type MyTypeConstraint interface {
~int | ~string
}
Is there a way to check if given value satisfies this constraint aside from comparing value to each type inside MyTypeConstraint using switch reflect.TypeOf(v) statement? For example, here I don't want user to pass v which type doesn't satisfy constraint into function:
type ErrNode struct {
Data map[string]interface{}
// Err error -- irrelevant
// next *ErrNode -- irrelevant
}
// `GetData()` is constrained but `Set()` is not.
// Of course I could pass `ErrNode` as parameter into `Set()`
// like bellow but then I won't be able to chain `Set()` calls.
func GetData[T ErrData](list *ErrNode, k string) (v T, ok bool) {
v, ok = list.Data[k].(T)
return v, ok
}
func (e *ErrNode) Set(k string, v interface{}) (self *ErrNode) {
e.Data[k] = v // v must be of type listed in `MyTypeConstraint`
return e
}