Go Data Structures: Interfaces
go's interfaces—static, checked at compile time, dynamic when asked for—are, for me, the most exciting part of go from a language design point of view. if i could export one feature of go into other languages, it would be interfaces.
this post is my take on the implementation of interface values in the “gc” compilers: 6g, 8g, and 5g. over at airs, ian lance taylor has written about the implementation of interface values in gccgo
. the implementations are more alike than different: the biggest difference is that this post has pictures.
before looking at the implementation, let's get a sense of what it must support.
usage
go's interfaces let you use duck typing like you would in a purely dynamic language like python but still have the compiler catch obvious mistakes like passing an int
where an object with a read
method was expected, or like calling the read
method with the wrong number of arguments. to use interfaces, first define the interface type (say, readcloser
):
type readcloser interface { read(b []byte) (n int, err os.error) close() }
and then define your new function as taking a readcloser
. for example, this function calls read
repeatedly to get all the data that was requested and then calls close
:
func readandclose(r readcloser, buf []byte) (n int, err os.error) { for len(buf) > 0 && err == nil { var nr int nr, err = r.read(buf) n += nr buf = buf[nr:] } r.close() return }
the code that calls readandclose
can pass a value of any type as long as it has read
and close
methods with the right signatures. and, unlike in languages like python, if you pass a value with the wrong type, you get an error at compile time, not run time.
interfaces aren't restricted to static checking, though. you can check dynamically whether a particular interface value has an additional method. for example:
type stringer interface { string() string } func tostring(any interface{}) string { if v, ok := any.(stringer); ok { return v.string() } switch v := any.(type) { case int: return strconv.itoa(v) case float: return strconv.ftoa(v, 'g', -1) } return "???" }
the value any
has static type interface{}
, meaning no guarantee of any methods at all: it could contain any type. the “comma ok” assignment inside the if
statement asks whether it is possible to convert any
to an interface value of type stringer
, which has the method string
. if so, the body of that statement calls the method to obtain a string to return. otherwise, the switch
picks off a few basic types before giving up. this is basically a stripped down version of what the does. (the if
could be replaced by adding case stringer:
at the top of the switch
, but i used a separate statement to draw attention to the check.)
as a simple example, let's consider a 64-bit integer type with a string
method that prints the value in binary and a trivial get
method:
type binary uint64 func (i binary) string() string { return strconv.uitob64(i.get(), 2) } func (i binary) get() uint64 { return uint64(i) }
a value of type binary
can be passed to tostring
, which will format it using the string
method, even though the program never says thatbinary
intends to implement stringer
. there's no need: the runtime can see that binary
has a string
method, so it implements stringer
, even if the author of binary
has never heard of stringer
.
these examples show that even though all the implicit conversions are checked at compile time, explicit interface-to-interface conversions can inquire about method sets at run time. “effective go” has more details about and examples of how interface values can be used.
interface values
languages with methods typically fall into one of two camps: prepare tables for all the method calls statically (as in c++ and java), or do a method lookup at each call (as in smalltalk and its many imitators, javascript and python included) and add fancy caching to make that call efficient. go sits halfway between the two: it has method tables but computes them at run time. i don't know whether go is the first language to use this technique, but it's certainly not a common one. (i'd be interested to hear about earlier examples; leave a comment below.)
as a warmup, a value of type binary
is just a 64-bit integer made up of two 32-bit words (like in the , we'll assume a 32-bit machine; this time memory grows down instead of to the right):
interface values are represented as a two-word pair giving a pointer to information about the type stored in the interface and a pointer to the associated data. assigning b
to an interface value of type stringer
sets both words of the interface value.
(the pointers contained in the interface value are gray to emphasize that they are implicit, not directly exposed to go programs.)
the first word in the interface value points at what i call an interface table or itable (pronounced i-table; in the runtime sources, the c implementation name is itab
). the itable begins with some metadata about the types involved and then becomes a list of function pointers. note that the itable corresponds to the interface type, not the dynamic type. in terms of our example, the itable for stringer
holding type binary
lists the methods used to satisfy stringer
, which is just string
: binary
's other methods (get
) make no appearance in the itable.
the second word in the interface value points at the actual data, in this case a copy of b
. the assignment var s stringer = b
makes a copy of b
rather than point at b
for the same reason that var c uint64 = b
makes a copy: if b
later changes, s
and c
are supposed to have the original value, not the new one. values stored in interfaces might be arbitrarily large, but only one word is dedicated to holding the value in the interface structure, so the assignment allocates a chunk of memory on the heap and records the pointer in the one-word slot. (there's an obvious optimization when the value does fit in the slot; we'll get to that later.)
to check whether an interface value holds a particular type, as in the above, the go compiler generates code equivalent to the c expression s.tab->type
to obtain the type pointer and check it against the desired type. if the types match, the value can be copied by by dereferencing s.data
.
to call s.string()
, the go compiler generates code that does the equivalent of the c expression s.tab->fun[0](s.data)
: it calls the appropriate function pointer from the itable, passing the interface value's data word as the function's first (in this example, only) argument. you can see this code if you run 8g -s x.go
(details at the bottom of this post). note that the function in the itable is being passed the 32-bit pointer from the second word of the interface value, not the 64-bit value it points at. in general, the interface call site doesn't know the meaning of this word nor how much data it points at. instead, the interface code arranges that the function pointers in the itable expect the 32-bit representation stored in the interface values. thus the function pointer in this example is (*binary).string
not binary.string
.
the example we're considering is an interface with just one method. an interface with more methods would have more entries in the fun list at the bottom of the itable.
computing the itable
now we know what the itables look like, but where do they come from? go's dynamic type conversions mean that it isn't reasonable for the compiler or linker to precompute all possible itables: there are too many (interface type, concrete type) pairs, and most won't be needed. instead, the compiler generates a type description structure for each concrete type like binary
or int
or func(map[int]string)
. among other metadata, the type description structure contains a list of the methods implemented by that type. similarly, the compiler generates a (different) type description structure for each interface type like stringer
; it too contains a method list. the interface runtime computes the itable by looking for each method listed in the interface type's method table in the concrete type's method table. the runtime caches the itable after generating it, so that this correspondence need only be computed once.
in our simple example, the method table for stringer
has one method, while the table for binary
has two methods. in general there might be ni methods for the interface type and nt methods for the concrete type. the obvious search to find the mapping from interface methods to concrete methods would take o(ni × nt) time, but we can do better. by sorting the two method tables and walking them simultaneously, we can in o(ni + nt) time instead.
memory optimizations
the space used by the implementation described above can be optimized in two complementary ways.
first, if the interface type involved is empty—it has no methods—then the itable serves no purpose except to hold the pointer to the original type. in this case, the itable can be dropped and the value can point at the type directly:
whether an interface type has methods is a static property—either the type in the source code says interface{}
or it says interace{ methods... }
—so the compiler knows which representation is in use at each point in the program.
second, if the value associated with the interface value can fit in a single machine word, there's no need to introduce the indirection or the heap allocation. if we define binary32
to be like binary
but implemented as a uint32
, it could be stored in an interface value by keeping the actual value in the second word:
whether the actual value is being pointed at or inlined depends on the size of the type. the compiler arranges for the functions listed in the type's method table (which get copied into the itables) to do the right thing with the word that gets passed in. if the receiver type fits in a word, it is used directly; if not, it is dereferenced. the diagrams show this: in the binary
version far above, the method in the itable is(*binary).string
, while in the binary32
example, the method in the itable is binary32.string
not (*binary32).string
.
of course, empty interfaces holding word-sized (or smaller) values can take advantage of both optimizations:
method lookup performance
smalltalk and the many dynamic systems that have followed it perform a method lookup every time a method gets called. for speed, many implementations use a simple one-entry cache at each call site, often in the instruction stream itself. in a multithreaded program, these caches must be managed carefully, since multiple threads could be at the same call site simultaneously. even once the races have been avoided, the caches would end up being a source of memory contention.
because go has the hint of static typing to go along with the dynamic method lookups, it can move the lookups back from the call sites to the point when the value is stored in the interface. for example, consider this code snippet:
1 var any interface{} // initialized elsewhere 2 s := any.(stringer) // dynamic conversion 3 for i := 0; i < 100; i++ { 4 fmt.println(s.string()) 5 }
in go, the itable gets computed (or found in a cache) during the assignment on line 2; the dispatch for the s.string()
call executed on line 4 is a couple of memory fetches and a single indirect call instruction.
in contrast, the implementation of this program in a dynamic language like smalltalk (or javascript, or python, or ...) would do the method lookup at line 4, which in a loop repeats needless work. the cache mentioned earlier makes this less expensive than it might be, but it's still more expensive than a single indirect call instruction.
of course, this being a blog post, i don't have any numbers to back up this discussion, but it certainly seems like the lack of memory contention would be a big win in a heavily parallel program, as is being able to move the method lookup out of tight loops. also, i'm talking about the general architecture, not the specifics o the implementation: the latter probably has a few constant factor optimizations still available.
more information
the interface runtime support is in $goroot/src/pkg/runtime/iface.c
. there's much more to say about interfaces (we haven't even seen an example of a pointer receiver yet) and the type descriptors (they power reflection in addition to the interface runtime) but those will have to wait for future posts.
code
supporting code (x.go
):
package main import ( "fmt" "strconv" ) type stringer interface { string() string } type binary uint64 func (i binary) string() string { return strconv.uitob64(i.get(), 2) } func (i binary) get() uint64 { return uint64(i) } func main() { b := binary(200) s := stringer(b) fmt.println(s.string()) }
selected output of 8g -s x.go
:
0045 (x.go:25) leal s+-24(sp),bx 0046 (x.go:25) movl 4(bx),bp 0047 (x.go:25) movl bp,(sp) 0048 (x.go:25) movl (bx),bx 0049 (x.go:25) movl 20(bx),bx 0050 (x.go:25) call ,bx
the leal
loads the address of s
into the register bx
. (the notation n(sp)
describes the word in memory at sp+n
. 0(sp)
can be shortened to (sp)
.) the next two movl
instructions fetch the value from the second word in the interface and store it as the first function call argument, 0(sp)
. the final two movl
instructions fetch the itable and then the function pointer from the itable, in preparation for calling that function.
原文位置: https://research.swtch.com/interfaces
推荐阅读
-
PNG Data structures
-
【Data structures】283题_移动零
-
Go Data Structures: Interfaces
-
mandliya / algorithms_and_data_structures使用Qt打开编译报错解决办法
-
[译]The Python Tutorial#Data Structures
-
详细介绍php中的Data Structures扩展
-
Python 官方文档 中文版 5. Data Structures
-
【Data structures】283题_移动零
-
[译]The Python Tutorial#Data Structures
-
PHP7.2 Data Structures的使用