crunk1
crunk1

Reputation: 2818

How to cast nil interface to nil other interface

I have a classic Go nil interface issue.

I'm trying to assert an interface{}, which I assign from a nil error, back to an error interface. That sentence is confusing so I have a handy-dandy example: https://play.golang.com/p/Qhv7197oIE_z

package main

import (
    "fmt"
)

func preferredWay(i interface{}) error {
    return i.(error)
}

func workAround(i interface{}) error {
    if i == nil {
        return nil
    }
    return i.(error)
}

func main() {
    var nilErr error
    fmt.Println(workAround(nilErr))    // Prints "<nil>" as expected.
    fmt.Println(preferredWay(nilErr))  // Panics.
}

Output:

<nil>
panic: interface conversion: interface is nil, not error

goroutine 1 [running]:
main.preferredWay(...)
    /tmp/sandbox415300914/prog.go:8
main.main()
    /tmp/sandbox415300914/prog.go:21 +0xa0

So in other words, I'm trying to downcast from a nil interface{} to a nil error interface. Is there an elegant way to do this if I know the interface{} was assigned as a nil error to begin with?

FYI, if this seems unusual, it's because I'm implementing some mocking for testing.

Upvotes: 2

Views: 3636

Answers (1)

Burak Serdar
Burak Serdar

Reputation: 51567

Does this work?

func preferredWay(i interface{}) error {
    k, _ := i.(error)
    return k
}

Upvotes: 6

Related Questions