Golang sum types

Has anyone here found a tolerable way to do sum types in GoLang ?

For certain domains, GoLang has better libraries than RustLang (for example, Pion vs webrtc-rs port). However, every time I try to use GoLang, the feature I miss most from Rust is sum types. I can tolerate the lack of borrow checker, but the lack of sum types is very annoying when dealing with network ipc (which is guaranteed for GoLang <-> Rust communication.)

Has anyone here found a tolerable way to do sum types in GoLang ?

I think you will have better luck asking in https://forum.golangbridge.org/. But, let me try to answer.

So far, I don't have a way to do sum type ergonomically in Go yet. One way is we can use interface with private method, then create a bunch of structs that implements that private method. By doing this, you can have fixed number of implementation since other package outside can't implement the private method. One example is in the Go's AST package ast package - go/ast - Go Packages, the Expr interface is a sum type in a way. But, this is not exactly the same as Rust' enum since their memory layout is different. This approach is more like sealed class in Kotlin.

1 Like

See also: GitHub - BurntSushi/go-sumtype: A simple utility for running exhaustiveness checks on Go "sum types."


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.