Sobes.tech
Junior — Middle

When can an interface have a nil value or be undefined in programming?

sobes.tech AI

Answer from AI

In Go, an interface can be nil or undefined in the following cases:

  1. Interface variable is uninitialized If an interface variable is declared but not assigned a value, it is nil.

  2. Interface contains a nil pointer An interface in Go consists of two parts: type and value. If the type is set, but the value is a nil pointer (nil), then the interface is not equal to nil, although the internal value is absent.

  3. Passing nil to an interface If you pass a value of nil of a specific type to an interface (for example, (*MyStruct)(nil)), the interface will not be nil because the type is present.

Example:

var i interface{} // i == nil

var p *int = nil
i = p // i != nil, because the type *int is present, but the value is nil

if i == nil {
    fmt.Println("i is nil")
} else {
    fmt.Println("i is not nil")
}

This is important to consider when checking for nil to avoid false positives.

When can an interface have a nil value or be… - sobes.tech