Hi @Chenchen_Liu !!
Let’s address your questions one by one:
-
What is iface?
-
iface
is a struct defined in the Go runtime package (runtime2.go
). It is used to represent interface values internally. An interface in Go consists of two components: a type descriptor (itab
) and a pointer to the value that implements the interface (data
). The iface
struct holds references to these components.
-
Why is a nil pointer to a type actually an interface?
- In Go, a nil pointer to a type is treated as an interface when necessary because an interface value in Go is represented by a pair of pointers, as mentioned above. When a nil pointer is assigned to an interface, the interface’s
data
pointer is set to nil, indicating that the interface is “empty” or “uninitialized”.
-
var err *OSError; err == nil
// this is true. why?
- In Go, when you declare a variable of a pointer type (like
var err *OSError
), if you don’t explicitly initialize it, the zero value of the pointer type is assigned, which is nil
for pointer types. So, in the case of var err *OSError
, err
is indeed initialized to nil
. Hence, err == nil
evaluates to true
.
In summary, in Go, a nil pointer to a type is treated as an interface, and declaring a pointer variable without initialization assigns it the nil value, which is why var err *OSError; err == nil
evaluates to true.
Happy Learning