Sobes.tech
Principal

How to check if the value inside interface{} equals nil (write code)?

sobes.tech AI

Answer from AI

In Go, to check if a value of type interface{} is nil, you need to check both the interface itself and its internal value. Example:

var val interface{}

if val == nil {
    // val is nil
}

// If val contains a pointer or another type, check the internal value using reflect:
import "reflect"

func isNil(i interface{}) bool {
    if i == nil {
        return true
    }
    v := reflect.ValueOf(i)
    switch v.Kind() {
    case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
        return v.IsNil()
    }
    return false
}

// Usage:

var x interface{} = (*int)(nil)
fmt.Println(isNil(x)) // true

var y interface{} = 0
fmt.Println(isNil(y)) // false

Since interface{} contains a type and a value, a simple comparison with nil is only true if both the type and the value are absent.