I'm curious on what kind of patterns should used in Go for such cases. So let's suppose, you have a Request
struct that holds some information for making an HTTP request, along with the parameters that can be sent in the payload and their respective validations. Now different type of validations would be applicable on the basis of the data type of the parameter, so I decided to use a map[string]Validations
, where I could store the type of Validations mentioned in the Validations
union (basically, being able to accomodate both IntValidations
& StrValidations
in the same map).
But the below code would result in an error because Validations
can only be used as a type parameter, so how can we achieve this in Go? In Java this could be easily achieved with polymorphism, where Validation
would be the parent class and int and float validations would be the child classes, so later on we could easily instantiate a HashMap
of Validations
.
Note: I would want to avoid the usage of map[string]interface{}
.
type Validations interface {
IntValidations | StrValidations
}
type IntValidations struct {
MaxVal int
MinVal int
}
type StrValidations struct {
MinLength int
MaxLength int
Regex string
}
type Request struct {
Path string
Payload map[string]Validations // Error: Validations cannot be used outside of a type constraint.
}
map[string]Validation
whereValidation
is an interface with methods appropriate for a validation. Exampletype Validation interface { Do(<insert args here>) error }
Do
methods on theIntValidation
andStrValidations
types. See the Tour of Go for information on how to implement a method and how methods relate to interfaces.