A little bit of context. I'm trying to develop a parser combinators library for Go inspired in Nom (parser combinators library for Rust https://github.com/rust-bakery/nom).
Now I'm trying to implement a generic Map function for type Parser, in order to allow to user to map a parser result into another result. Here is the code that I have:
type Parser[O any] func(string) (string, O, error)
type MapFn[U any, K any] func(parsed U) (K, error)
func (p Parser[O]) Map(mapper MapFn[O, any]) Parser[any] {
return func(s string) (string, any, error) {
next, p1, err := p(s)
if err != nil {
return "", nil, err
}
p2, err := mapper(p1)
if err != nil {
return "", nil, err
}
return next, p2, nil
}
}
Notice that the signature of the mapper (MapFn) takes two generic arguments, the original parsed result and the new mapped result type. The issue is that I cannot pass the new mapped result type to the Map method for the parser because it is generic and it is not allowed.
The easiest solution is just set the mapped result type as any, but I dont like the behaviour because I want to provide a "type safe" parsers; so use any will lead to cumbersome type assertions all the way.
So, Is there any way, package, workaround or pattern to allow generics in methods?