How to try catch type conversion in golang

Viewed 39

In my function I get a a parameter. I need to convert this parameter. I want to convert this parameter to continue working with it

func IncWebhookRequestCount(obj something) {
    a := obj.(*pkg.CustomType1)
    a = obj.(*pkg.CustomType2)
}

I know that I am always able to convert it into CustomType1 or CustomType2. I do not care which one a is. How can I try converting into CustomType1 and if that does not work fall back to ?CustomType2.

Currently I get a panic: interface conversion

2 Answers

If you have multiple types to handle, the simplest solution is to use a type switch:

func IncWebhookRequestCount(obj something) {
    switch v := obj.(type) {
    case *pkg.CustomType1:
        // here v is of type *pkg.CustomType1
    case *pkg.CustomType2:
        // here v is of type *pkg.CustomType2
    default:
        // none of the above
    }
}

If you want to check just a single type, the special form of the type assertion is shorter and clearer:

if v, ok := obj.(*pkg.CustomType1); ok {
    // obj is not nil and v is of type *pkg.CustomType1
} else {
    // obj is nil or holds a value not of type *pkg.CustomType1
}

Something like this:

func IncWebhookRequestCount(obj something) {
    var a any

    switch t := obj.(type) {
    case *pkg.CustomType1:
       a = obj.(*pkg.CustomType1)
    case *pkg.CustomType2:
       a = obj.(*pkg.CustomType2)
    default:
       fmt.Printf("Unknown type: %v\n", t)
    }
}

Also something should be an interface{}.

You can also test to avoid panic:

a, ok := a.(*sometype)
if !ok {
  fmt.Println("a is not of type *sometype")
}
Related