How to log type assertion errors in golang?

Prateek picture Prateek · Jun 3, 2016 · Viewed 11.6k times · Source

I have an array of some data which I want to map in []string. I can do it in 2 ways:

a)

// someData
s := someData.([]string)

In this case, the execution would stop after listing the error on the console.

b)

// someData
s, ok := someData.([]string)

In this case, no errors would occur but s will have its zero-value


I want to log the errors in such type assertion failure cases without stopping the execution. However, when I am using type (b), I cannot see the error details.

The only solution I can think is to use reflect.TypeOf and print both the types.

Is there any other way we can get the error when using solution (b)?

Answer

Paul Hankin picture Paul Hankin · Jun 3, 2016

You can construct the log message yourself. There's no need for explicit calls to reflect as there's a printf format string %T that produces the type.

s, ok := someData.([]string)
if !ok {
    log.Printf("got data of type %T but wanted []string", someData)
    ... handle the failure somehow
}

Without knowing the context it's hard for me to produce a useful and informational log statement, but you can adapt the idea to suit your use case.