Back to questions
JuniorTheoryCommon
What does the program print?
package main
import "fmt"
type Rect struct{ W, H float64 }
func main() {
var r *Rect
var s any = r
fmt.Println(r == nil, s == nil, s.(*Rect) == nil)
}true false true
- Expecting
true true true: an interface value isnilonly when both its type and its value are empty, andsalready holds the type*Rect. - Expecting a panic at
s.(*Rect): the assertion succeeds because the dynamic type is*Rect, and it returns the nil pointer, so== nilistrue.
- Why can a function that returns
errorhand back a non-nil error that holds a nil pointer? - What would
s == nilprint right aftervar s any, before the assignment?