0

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?

4
  • Assuming it's possible to implement the function the way you like, how this specialisation should be compiled: parser[int]("false")?
    – zerkms
    Commented Aug 7 at 4:44
  • @zerkms It looks like OP expects the type parameter to select the specialization, not the value of the string. Commented Aug 7 at 5:04
  • @CeriseLimón that's why I specified the type parameter explicitly, yep. I just still fail to understand what it should compile for the bool branch: the bool storage for return value would be not enough to hold the int value from the case int: branch. So it's not obvious what return v, nil there would do.
    – zerkms
    Commented Aug 7 at 5:38
  • @zerkms Thank you for the context. I have a better understanding now of why something like that wouldn't be possible, at least currently. I'm intrigued by the open proposal to allow for something at least close to what I was trying here.
    – Gabe
    Commented Aug 8 at 21:19

1 Answer 1

4

Use plain functions. The code is simpler and shorter.

func parseBool(value string) bool {
    v, _ := strconv.ParseBool(value)
    return v
}

func parseInt(value string) int {
    v, _ := strconv.Atoi(value)
    return v
}

func main() {
    parsedBool := parseBool("true")
    parsedInt := parseInt("2024")
}

https://go.dev/play/p/PkKTZSjvh8_y

Not the answer you're looking for? Browse other questions tagged or ask your own question.