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:
-
Interface variable is uninitialized If an interface variable is declared but not assigned a value, it is
nil. -
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 tonil, although the internal value is absent. -
Passing
nilto an interface If you pass a value ofnilof a specific type to an interface (for example,(*MyStruct)(nil)), the interface will not benilbecause 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.