Hello
I’m not good at English, so this topic is written by the translator. Please understand.
i’m started learning Go 2 weeks ago. I have been programming mainly in the C language. I’m interested in generic pattern using void pointer. I want to implement a similar form in go.
I know that Go doesn’t support generic grammar but can do something similar through the interface.
this is example from a book i’m reading
type fType func(int, int) int
func errorHandler(fn fType) fType {
return func(a int, b int) int {
defer func() {
if err, ok := recover().(error); ok {
log.Printf("run time panic: %v", err)
}
}()
return fn(a, b)
}
}
func divide(a int, b int) int {
return a / b
}
I want to change errorHandler argument to generic style. I know that “interface{}” has a similar function to “void *”. Here is my code.
type gfType func(...interface{}) interface{}
func gErrorHandler(gfn gfType) gfType {
return func(a ...interface{}) interface{} {
defer func() {
if err, ok := recover().(error); ok {
log.Printf("run time panic: %v", err)
}
}()
return gfn(a...)
}
}
func divide(arg ...interface{}) interface{} {
a := arg[0].(int)
b := arg[1].(int)
return a / b
}
I wonder if this is the way Go is directed.
I’ve implemented it through interface, but I don’t think there’s any advantage.
type runner interface {
run() interface{}
}
func iErrorHandler(r runner) interface{} {
defer func() {
if err, ok := recover().(error); ok {
log.Printf("run time panic: %v", err)
}
}()
return r.run()
}
type div struct {
a, b int
}
func (d div) run() interface{} {
return d.a / d.b
}
Thank you for reading my topic.