Home >Backend Development >Golang >How to use string enum with method as generic parameter?
php editor Youzi is here to introduce how to use string enumeration with methods as generic parameters. In programming, we often need to use generics to increase the flexibility and reusability of code. Using string enumerations with methods as generic parameters can make our code more concise and efficient. Next, we will elaborate on how to implement this function and give specific example code. Let’s explore this interesting programming technique together!
I have multiple string-derived enumerations that share a common validate()
method (all beyond my control). I want a generic method that converts strings to these enums and calls validate()
on the resulting enums. I tried using generics to achieve this but failed for various reasons.
In the following example, the type constraint is too strong and validate()
cannot be called. I also tried using the validate()
method to insert my own interface and use it as a type constraint, but then it failed on the type conversion part.
How to achieve this without modifying the enum?
package main // imagine i have multiple of those types outside of my control type FooStatusEnum string func NewFooStatusEnum(value FooStatusEnum) *FooStatusEnum { return &value } const ( FooStatusEnumA FooStatusEnum = "A" FooStatusEnumB FooStatusEnum = "B" FooStatusEnumC FooStatusEnum = "C" ) func (m FooStatusEnum) Validate() error { return nil } func stringToValidatedEnum[E ~string](s string) E { e := E(s) if err := e.Validate(); err != nil { panic(1) } return e } func main() { stringToValidatedEnum[FooStatusEnum]("A") e := FooStatusEnum("A") e.Validate() }
Use type constraints specifying the string
base type and validate()
method:
type enumstring interface { ~string validate() error } func stringtovalidatedenum[e enumstring](s string) e { e := e(s) if err := e.validate(); err != nil { panic(1) } return e }
Test it:
result := stringtovalidatedenum[foostatusenum]("a") fmt.printf("%t %v", result, result)
This will output (try it on go playground):
main.FooStatusEnum A
The above is the detailed content of How to use string enum with method as generic parameter?. For more information, please follow other related articles on the PHP Chinese website!