Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 147 ยท Interfaces

Interface Internals and the nil Trap

Understand how Go stores interface values as a (type, value) pair, why an interface holding a nil pointer is not nil, how interfaces compare, what dynamic dispatch costs and how embedding works.

Interfaces in Go look simple on the surface: a set of methods, satisfied implicitly. Underneath, an interface value is a small two-part structure, and almost every surprising interface behavior follows from it. Why is err != nil sometimes true when the function "returned nil"? Why can comparing two interfaces panic? How much does calling a method through an interface cost? And what actually happens when you put one interface inside another?

This lesson answers those questions with experiments. You will learn the mental model (a pair of dynamic type and dynamic value), meet the famous nil trap, see the rules for comparing interface values, look at what dynamic dispatch costs, and finish with interface embedding. You should be comfortable with interfaces, pointers and type assertions first.

An interface value is a pair

Think of an interface value as two words side by side:

TEXT
interface value
+-----------------+-----------------+
| dynamic type    | dynamic value   |
| (what is it?)   | (the data)      |
+-----------------+-----------------+

The dynamic type records which concrete type is stored. The dynamic value is the data itself (or a pointer to it, when it is too big to fit). For an interface with methods, the first word is really a pointer to a table of the type's methods for that interface (an itab), but the model "type plus value" is all you need to reason about behavior. In the runtime, an any is two machine words and a non-empty interface is two as well, so both are 16 bytes on a 64-bit system:

Go What an interface value looks like

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

An interface variable that was never assigned is nil: both parts are empty, and %T prints <nil>. After assigning a Square, the type part says main.Square and the value part holds the copy of the struct. The interface is always 16 bytes no matter how large the stored value is, because larger values live elsewhere and the interface points to them.

Assigning a value to an interface copies it. If you store a struct in an any and later change the original variable, the interface still holds the old copy. To share mutable state through an interface, store a pointer.

The nil trap

Here is the rule that causes the most confusion: an interface value is nil only when both its type and its value are empty. If the type part is set, the interface is not nil, even if the value part is a nil pointer.

Go A nil pointer inside a non-nil interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

After g = p, the interface holds the pair (*English, nil). Its type part is set, so g == nil is false. The method call still works because the compiler knows which method to call from the type and passes the nil pointer as the receiver. Whether that is safe depends on the method: this one checks for nil, others would crash with a nil pointer dereference.

The classic bug: returning a nil pointer as an error

The trap bites hardest with error. A function whose return type is error returns an interface. If you return a typed nil pointer there, callers see a non-nil error:

Go The typed nil error bug and its fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

validateBuggy(5) declares err as *MyError, never assigns it, and returns it. The conversion to error produces (*MyError, nil), which is not equal to nil. The caller then believes something failed, and calling err.Error() would crash with a nil dereference. Any time a function returns an interface, return the untyped nil literal on the success path, and never declare a variable of a concrete pointer type just to return it as an interface. The Custom Error Types lesson shows this trap again in the context of errors, and go vet has checks that catch some variants.

The rule of thumb: functions that return an interface should return nil, not a variable of a concrete pointer type that happens to be nil.

Comparing interface values

You can compare interface values with == and !=. Two interface values are equal when they have identical dynamic types and equal dynamic values (or are both nil). Comparing an interface with a concrete value works too, if the concrete type implements the interface:

Go Equality of interface values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Values of different dynamic types are never equal, even if they hold the same number, which is why 1 and int64(1) differ. Two pointers are equal when they point at the same variable.

Comparing uncomparable types panics

Slices, maps and functions cannot be compared with ==. The compiler stops you when it can see the types, but behind an interface it can only find out at run time. If both dynamic types are the same uncomparable type, the comparison panics:

Go Comparing slices through any (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first comparison is false without trouble. The second panics with runtime error: comparing uncomparable type []int. The same applies when an interface is used as a map key: m[a] with a slice inside panics with runtime error: hash of unhashable type []int. If your code accepts any and compares or hashes the values, document that or protect it with reflect.TypeOf(v).Comparable().

What dynamic dispatch costs

When you call a method on a concrete type, the compiler usually knows exactly which function to call and can even inline it. Through an interface, the call goes through the itab: load the method's address from the table, then call it indirectly. This is called dynamic dispatch.

The cost is small, typically a couple of nanoseconds, but real in tight loops, because an indirect call usually cannot be inlined. There is a second cost: putting a value in an interface can force a heap allocation. You can measure allocations deterministically with testing.AllocsPerRun, which the lesson on Stack, Heap and Escape Analysis uses extensively:

Go Counting allocations caused by interfaces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Storing a changing integer in an any allocates, since the interface needs somewhere to keep the value. Storing a constant or a pointer typically does not. This is one reason hot paths avoid any and why generics can be faster for numeric code (compare Generics in Practice).

Do not let this scare you off interfaces. Calls through interfaces are fast enough for the vast majority of code, and clear design matters more. Measure before you optimize; the Go compiler can also devirtualize some interface calls when it can prove the concrete type, and profile-guided optimization can inline hot dynamic calls.

Embedding interfaces

An interface can include other interfaces by listing them inside its definition. The method set of the new interface is the union of all of them. This is how the standard library builds io.ReadWriter and io.ReadCloser:

Go Building larger interfaces from small ones

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

f satisfies Reader and Writer automatically, so it can be passed to copyOne. The reverse does not hold: a plain Reader is not a ReadWriteCloser unless the concrete value behind it happens to implement all three methods, which you can check with a type assertion.

Two embedded interfaces may list the same method as long as the signatures are identical (since Go 1.14). Conflicting signatures for the same name are a compile error.

Embedding an interface in a struct

Embedding also works in structs. A struct that embeds an interface gets all of the interface's methods promoted, and the field holds whatever implementation you give it. This is handy for decorating one method while delegating the rest (see Struct Embedding and Composition):

Go Overriding one method of an embedded interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The last two lines illustrate a danger: if you forget to set the embedded interface field, it is nil, and calling a method through it panics with a nil pointer dereference. Always construct such wrappers through a function that takes the inner value as a parameter.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print?

    var p *int; var x any = p; fmt.Println(x == nil)

    x holds the pair (*int, nil). Its type part is set, so the interface is not nil, even though the pointer inside is.
  2. 2. How can a function that returns error avoid the typed-nil trap?

    Returning untyped nil gives an interface with both parts empty, so err != nil is false for callers.
  3. 3. What is the result of var a, b any = 1, int64(1); fmt.Println(a == b)?

    Interface values are equal only if their dynamic types are identical. int and int64 are different types, so the result is false.
  4. 4. What happens when you run var a, b any = []int{1}, []int{1}; _ = a == b?

    The compiler cannot see the types behind any, so it compiles. At run time both dynamic types are []int, which is uncomparable, so the comparison panics.
  5. 5. A struct embeds an io.Reader field but never sets it. What happens on s.Read(buf)?

    The promoted method is called through the nil interface field, which panics.

Summary

  • An interface value is a pair: a dynamic type and a dynamic value. It is 16 bytes on 64-bit systems.
  • An interface is nil only when both parts are empty. A nil pointer stored in an interface gives a non-nil interface.
  • Return the literal nil from functions that return interfaces such as error; do not return a nil variable of a concrete pointer type.
  • Interfaces compare equal when types are identical and values are equal; comparing uncomparable dynamic types (slices, maps, funcs) panics at run time, and so does using them as map keys.
  • Method calls through an interface use dynamic dispatch; the cost is small, but boxing values can allocate.
  • Interfaces can embed other interfaces to build larger method sets, and structs can embed an interface to decorate or wrap an implementation.

Next: Designing with Interfaces shows how to use all of this to structure real programs.