I'm trying to write a generic parser that would do different things depending on the expected return type. As simplified example of what I'd like to do, already using a trick from another answer:
func parser[T any](value string) T {
var ret T
switch v := any(ret).(type) {
case bool:
v, _ = strconv.ParseBool(value)
return v, nil
case int:
v, _ = strconv.Atoi(value)
return v, nil
}
}
func main() {
parsedBool := parser[bool]("true")
parsedInt := parser[int]("2024")
}
The example doesn't work, with:
cannot use v (variable of type bool) as T value in return statement
cannot use v (variable of type int) as T value in return statement
Is there a way to have a generic method execute different logic depending on the type(s) it's handling?
parser[int]("false")
?bool
branch: thebool
storage forreturn
value would be not enough to hold theint
value from thecase int:
branch. So it's not obvious whatreturn v, nil
there would do.