5 ms·
I really like most things about Go, and was even going to use it for a bytecode interpreter project I was working on. A problem that I ran into, however, was th
by ek 15y ago
I really like most things about Go, and was even going to use it for a bytecode interpreter project I was working on. A problem that I ran into, however, was that in interpreting a dynamic language with a stack machine, we needed a way to be able to store arbitrary data in stack values, which in C/C++ would be done using a struct with a type flag and then a union of various types.
Go doesn't have unions, though, and so this means that we would have ended up using a struct and using about 3x the memory on average, per stack value. You can see this limitation exposed as well in goyacc, the port of Yacc to Go (as the name suggests). Where Bison uses a union for yylval, Go is forced to use a struct.
I think this has been discussed on the golang-nuts mailing list a couple times and dismissed, for reasons of which I'm not fully aware.
- chmike 15y agoUnions is a problem for garbage collectors. It is difficult to know if it contains a reference or a value. Though Go should have a solution for your use case. The only one I see is polymorphism. Thus a stack of references to different instances of the same class.
- ootachi 15y agoDiscriminated (type-safe) unions like ML and Haskell have are no problem for garbage collectors: you simply assign one ID to each variant of the union, and prefix the data with the ID corresponding to the variant in use. You can simulate ML-style unions in Go with interfaces and downcasts, or the reflect package (basically like case classes in Scala, but without the exhaustiveness checking). Unfortunately, downcasts in Go (and interfaces generally) are slow.
- jkn 15y agoCouldn't you use an empty interface to store arbitrary values? From the tutorial: Every type implements the empty interface, which makes it useful for things like containers. Unions are on the roadmap: http://golang.org/doc/devel/roadmap.html http://golang.org/doc/devel/roadmap.html but it's a list of ideas rather than features promised.
- JulianMorrison 15y agoC people: think of interface {} as roughly the same as void*, except that values pointed to preserve information about their type which can be extracted and used later.