Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Sum types are great in functional languages, but people are talking about using sum types in languages that don't natively support them. This blog post warns about misuse:

Abuse Of Some Sum Types In OO Languages http://www.jerf.org/iri/post/2960



Hmm, but that Go post argues that Sum types are only the right choice in a minority of situations and if you looked at, say, Rust you'd see APIs return sum types all over the place.

If we were to believe that "build yet another interface every time" was an equally good solution which is just a different flavour from sum types we'd expect to see equivalent APIs in Go with such interfaces and we do not. It's not a different style, it's just worse.

Example, suppose I got a string from a user, u, and I am now trying to see where that string is in another string I have from somewhere, x

In Rust x.find(u) returns Option<usize>, ie either None or Some(number)

But in Go strings.Index(x, u) returns int, and I have to know that the integer -1 is used as a sentinel value meaning "not found" rather than "found at position -1".

OK, so strings don't have great ergonomics, how about file opening? Let's open a file named george.txt which alas might not exist.

In Rust File::open("george.txt") returns Result<File>, ie either an Error or Ok(File)

But in Go os.Open("george.txt") return a tuple with both an error and my file and then I need to check whether the error was actually nil (no error).


I do think sum types would be a nice addition to Go, but this article is about the workarounds that people use since Go doesn't have them.

For example, if you're designing an API in Go, you should follow the established convention for error handling, rather than come up with your own weird thing, unless there's something special going on. Go's error handling is verbose but it's well understood and it's not broken.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: