Go's absence of generic capabilities poses challenges when attempting to generalize functionalities. A common scenario is the need for a generic error handling function applicable to any function returning a value and an error.
The provided example demonstrates an attempt to create such a function using an empty interface:
func P(any interface{}, err error) (interface{}) {
if err != nil {
panic("error: " err.Error())
}
return any
}
While this approach works for error handling, it loses type information, leaving the resulting interface empty.
To avoid the issue of lost type information, consider using code generation to create specialized implementations of the error handling function for different types. This can be achieved using tools like "go generate", "gengen", "genny", or "gen".
For example, using "gen", you can define a template:
// template.go
package main
import "fmt"
func P[T any](v T, err error) (T) {
if err != nil {
panic(fmt.Sprintf("error: %v", err))
}
return v
}
This template can be used to generate type-specific implementations of P():
gen generate
This will create implementations such as:
// p_int.go
package main
func PInt(v int, err error) (int) {
if err != nil {
panic(fmt.Sprintf("error: %v", err))
}
return v
}
By using these generated functions, type information is preserved and the error handling can be applied to specific types seamlessly.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3