educative.io

Question about interface

hello there,
please answer my questions belong:

  1. what is iface?
  2. why a nil pointer to a type is actually an interface?
  3. var err *OSError; err == nil // this is true. why?
    thanks

Course: https://www.educative.io/collection/10370001/5264931129131008
Lesson: https://www.educative.io/collection/page/10370001/5264931129131008/5946545022697472

Hi @Chenchen_Liu !!
Let’s address your questions one by one:

  1. 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.
  2. 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”.
  3. 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 :blush: