Dig101 — how Go implements interface values (eface, iface, itab)

Contents

  1. 1. 0x01 Same layout?
    1. 1.1. eface
    2. 1.2. iface
  2. 2. 0x02 Conversions between types
    1. 2.1. convXXX naming
    2. 2.2. Original convT2{I,E} and convI2I
    3. 2.3. Specialized convXXX paths
  3. 3. 0x03 Type assertions
    1. 3.1. Lookup
    2. 3.2. Insert / resize
    3. 3.3. Matching cost

Dig101: dig more, simplify more, know more

Runtime layout behind Go’s interface values — what “everything is an interface” looks like in memory.

An interface is a set of method signatures. It gives you contracts, abstractions, and constraints on implementations.

Values with no methods are the empty interface interface{}; in that sense every concrete value can live in an interface slot. (Before generics, interfaces were the usual stand-in for parametric code.)

Russ Cox on why interfaces matter:

From a language-design perspective, Go’s interfaces are static, checked at compile time, and dynamic when needed. If I could export one Go feature to other languages, it would be interfaces.
Go Data Structures: Interfaces

How is that represented in memory? How does duck typing work? What happens on a type assertion? Those are the questions below.

0x01 Same layout?

Two common ways to declare an interface — do they share the same runtime representation?

1
2
3
4
5
6
7
// style 1
var a interface{}
// style 2
type Stringer interface {
String() string
}
var b Stringer

No. They are different structs.

With GDB ptype on the variables:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// empty interface
>>> ptype a
type = struct runtime.eface {
runtime._type *_type;
void *data;
}
// interface with methods
>>> ptype b
type = struct runtime.iface {
runtime.itab *tab;
void *data;
}
>>> ptype b.tab
type = struct runtime.itab {
runtime.interfacetype *inter;
runtime._type *_type;
uint32 hash;
[4]uint8 _;
[1]uintptr fun;
} *
>>> ptype b.tab.inter
type = struct runtime.interfacetype {
runtime._type typ;
runtime.name pkgpath;
[]runtime.imethod mhdr;
} *

Go uses two interface representations; both are two machine words wide.

eface

Empty interface — no method set.

Stores concrete _type and data.

eface layout diagram

iface

Non-empty interface.

The itab field is richer than bare _type: it links concrete type, interface type, and method dispatch.

iface layout diagram

0x02 Conversions between types

When you assign into an interface, what fills those words?

1
2
3
4
5
6
7
8
9
10
11
type Binary uint64
func (i Binary) String() string {
return strconv.Itoa(int(i))
}

func conversion() {
var b Stringer
var i Binary = 1
b = i // what happens here?
println(b.String())
}

At b = i, the runtime calls something like convT64 from runtime/iface.go.

There are many convXXX helpers — what are they for?

convXXX naming

convFrom2To means convert from From to To.

From/To can be (see cmd/compile/internal/types/type.go:Tie):

  • E (eface)
  • I (iface)
  • T (concrete Type)

The set looks huge until you read specialize convT2x, don’t alloc for zero vals.

Original convT2{I,E} and convI2I

Initially: convT2{I,E} and convI2I.

They allocate (newobject) and copy (typedmemmove). convI2I also uses getitab (type assertions below).

The compiler (walkexpr) optimizes before calling them:

  • Fewer copies — pointer-shaped types or values that fit in one word can sit directly in data (main win).

    Pointer-shaped: ptr, chan, map, func, unsafe.Pointer. With type/itab stored, you only copy two words.

  • Fewer allocations — zero bool/byte can use zerobase / staticbytes; readonly globals; stack temporaries under 1 KiB that do not escape can be stored as {type/itab, &value}.

  • iface → eface — drop everything in itab except _type:

1
2
3
4
5
tmp = i.itab
if tmp != nil {
tmp = tmp.type
}
e = iface{tmp, i.data}

Specialized convXXX paths

Further tweaks:

  • Must allocated memory be zeroed? Pointer-shaped types need a clean slab; pointer-free types can be overwritten in place. On 32-bit, skipping convT64 when the value fits in one word keeps the store atomic.

  • Cheaper copy — for int, string, slice, etc., *(*Type)(x) = val instead of a generic memmove.

  • Write barrier? Pointer-shaped convT2{E,I} use typedmemmove (GC-aware). Pointer-free convT2{E,I}noptr use plain memmove.

walkexpr picks the function:

1
2
3
4
// cmd/compile/internal/gc/walk.go:walkexpr
case OCONVIFACE:
...
fnname, needsaddr := convFuncName(fromType, toType)
fnname From Store value by address (needsaddr)
convI2I iface no
convT{16,32,64} integer scalar, no pointers, align ≤ word no
convTstring string no
convTslice slice no
convT2E Type yes
convT2Enoptr pointer-free Type yes
convT2I Type yes
convT2Inoptr pointer-free Type yes

No convE2E or convE2I.
needsaddr: non-pointer types larger than 64 bits or unknown size use the address of the value in data.

0x03 Type assertions

Assertions dynamically check the concrete type. Success yields a typed value for method calls.

Implementations need not declare interfaces explicitly — so how does

1
2
3
4
5
6
7
8
9
10
11
type Binary uint64

func (i Binary) String() string {
return fmt.Sprint(i)
}

func typeAssert() {
var b interface{} = Binary(1)
v, ok := b.(Stringer)
println(v, ok)
}

know Binary implements Stringer?

The runtime calls assertE2I2:

  • assertE2I: v := eface1.(iface1)
  • assertE2I2: v, ok := eface1.(iface1)

The single-value form panics on failure.

Internally this hits the global itabTable mapping (interface type, concrete type) → itab.

1
2
3
4
5
6
const itabInitSize = 512
type itabTableType struct {
size uintptr
count uintptr
entries [itabInitSize]*itab
}

Lookup

getitab(inter, typ, canfail):

  • Lock-free read of itabTable; return if found
  • Else lock, search again
  • Else build itab, insert, unlock
  • On mismatch, panic or return ok == false per canfail

itabTable.find(inter, typ) for lookup; itabAdd(m) for insert.

Insert / resize

  • Before insert, m.fun is filled from the (m.inter, m._type) pair; m.fun[0] == 0 means “does not implement”.

  • When count exceeds 75% of capacity, grow (≥2×, aligned); swapping tables is atomic.

  • Probe from a hash of interface + concrete type into the open-address table (same family as map insertion).

Open addressing: h(i) = h0 + i*(i+1)/2 mod 2^k via itabTable.add(m).

Matching cost

Naive check: interface has ni methods, concrete type nt — double loop is O(ni*nt).

Go sorts itab.inter.mhdr and the concrete method list so one pass is O(ni+nt), then caches in the hash table.

Sketch from runtime/iface.go:init():

1
2
3
4
5
6
7
8
9
10
11
j:=0
imethods:
for k := 0; k < ni; k++ {
for ; j < nt; j++ {
if xxx { // type, pkgpath, name match
continue imethods
}
}
m.fun[0] = 0
}
m.fun[0] = uintptr(fun0)

Summary

  • eface vs iface, both two-word values
  • Conversions specialize on allocation, copy, and write barriers
  • Assertions reuse sorted method lists plus a global itab cache

See also: InterfaceSlice — why you cannot convert []Concrete to []interface{} directly.


Exercise: why does this assignment not call convT64?

1
2
var b Stringer = Binary(1)
_ = b.String()

Answer in a follow-up post.

Sample code: NewbMiao/Dig101-Go

Questions? Leave a comment below or email: newbvirgil@gmail.com