News for hackers. Stuff that matters.
Re:Go Replaces Interface{} with 'Any' by the_duke on Tuesday December 14, 2021 @05:04PM (#29558638)
Emulating sum types in languages without pattern matching is extremely awkward, to the point of being almost useless.

type Result[T] struct { ok: *T err: error }

Great, so how do you work with it?

* You can have a `ok()` getter that returns `*T`. Now you you need an `if x != nil`

* `isOk()` + `isErr()`

* `unwrap() T`, which panics on errors

* `split() (*T, err)` that splits into separate values, especially awkward since you both need `if err != nil` AND dereference the pointer

That API is more awkward then the status quo, and doesn't buy you any correctness guarantees because eventually you have to do an `if x := res.ok(); x != nil` or `x, err := res.split(); if err != nil {` anyway.

Pretty much the only convenience you gain are functions like `map()` or `unwrap_or`, but eventually you always have to take out the value and without being able to pattern match you can't get an API that improves correctness much.

(std::optional in C++ is a great example)

Re:Go Replaces Interface{} with 'Any' by linkdd on Tuesday December 14, 2021 @05:16PM (#29558825)
The Rust Result type has:

  - map / map_err
  - and_then / or_else
  - unwrap / unwrap_or
And countless of other functions making it very practical to chain computations without having to pattern match anything.

I do the same in Erlang/Elixir.

In Golang, I need to check every function call, and if I want to know where an error come from, I need to wrap it in an errors.New() because no exceptions = no stacktrace

Re:Go Replaces Interface{} with 'Any' by kbd on Tuesday December 14, 2021 @05:22PM (#29558916)
> and if I want to know where an error come from, I need to wrap it in an errors.New() because no exceptions = no stacktrace

Zig manages to provide traces with very little overhead:

https://ziglang.org/documentation/master/#Error-Return-Trace...

I am baffled as to why error handling in Go remains so impoverished.

Re:Go Replaces Interface{} with 'Any' by mariusor on Wednesday December 15, 2021 @02:46PM (#29570691)
Stack traces exist in go[1], I'm not sure why you consider exceptions to be the only way of getting a stack representation.

Not to mention that traditional exception handling advice I've been handed down from the gray beards is to always handle exceptions as early as possible, which is exactly what go forces you to do with their approach.

[1] https://pkg.go.dev/runtime/debug#Stack

Re:Go Replaces Interface{} with 'Any' by preseinger on Wednesday December 15, 2021 @02:42AM (#29563103)
Chaining computations hides the error control flow path, which negatively impacts readability.
Re:Go Replaces Interface{} with 'Any' by DarylZero on Tuesday December 14, 2021 @08:24PM (#29560797)
In general, you can replace pattern matching with a function that takes one function for each constructor of the sum type.

However, doing this kind of ... sucks.

Re:Go Replaces Interface{} with 'Any' by eru on Tuesday December 14, 2021 @11:48PM (#29562221)
It sucks when you have to use it for everything, but it's a useful enough technique that most Haskell datatypes come with functions that provide exactly this conversion to church encoding.

See eg 'maybe' (https://www.stackage.org/haddock/lts-18.18/base-4.14.3.0/Pre... on stackage) or foldr for lists.

'foldr' is interesting, because it encapsulates a recursive pattern matching on lists. For the non-recursive version, see 'uncons' composed with 'maybe'.

Re:Go Replaces Interface{} with 'Any' by DarylZero on Wednesday December 15, 2021 @01:36AM (#29562806)
It's probably actually better than pattern matching when there are only two, as in those cases. But even at three, it becomes a mess. And more than three? Yuck.
Re:Go Replaces Interface{} with 'Any' by eru on Thursday December 16, 2021 @03:58AM (#29576382)
If your language does currying similar to Haskell, and there's a good order to your constructors / arguments, even with three or more there might be some benefits with partial application.
Re:Go Replaces Interface{} with 'Any' by egeozcan on Tuesday December 14, 2021 @05:24PM (#29558950)
I don't see why that wouldn't be possible to implement now that the generics are here.
Re:Go Replaces Interface{} with 'Any' by linkdd on Tuesday December 14, 2021 @05:27PM (#29558975)
Which is exactly why I said:

> I cannot wait for the Result monad.

Generics make this possible, and will be a huge improvement to Go's error handling.

I'm not saying it will solve everything, but it's a huge step nonetheless.

Re:Go Replaces Interface{} with 'Any' by xyzzy_plugh on Tuesday December 14, 2021 @07:16PM (#29560114)
I think you will find that Go's error handling will not change as much as you suggest. The majority of developers are extremely cautious of generics and found the status quo to be the best balance between readability and conciseness.

Convenience is not a goal of the language, generally.

Re:Go Replaces Interface{} with 'Any' by saghm on Wednesday December 15, 2021 @01:29AM (#29562775)
> The majority of developers are extremely cautious of generics and found the status quo to be the best balance between readability and conciseness.

Most people who use Go have specifically chosen to use it though (or at least sought out opportunities, given that it's not something entrenched like Java being used due to inertia), so yes, most of them are fine with how Go is or they wouldn't be using it in the first place. If Go had generics from the start, I'd imagine most users would be fine with that too due to self-selection.

Re:Go Replaces Interface{} with 'Any' by Aeolun on Tuesday December 14, 2021 @11:16PM (#29562029)
It doesn’t need to be part of the core language. Everyone can make their own monad, or use the one from a library.
Re:Go Replaces Interface{} with 'Any' by egeozcan on Tuesday December 14, 2021 @06:01PM (#29559333)
I seem to have lost track of how the discussion reached that point, thanks for the clarification.
Re:Go Replaces Interface{} with 'Any' by eru on Tuesday December 14, 2021 @11:54PM (#29562259)
Depends on how generic you want this.

In Haskell, you can have functions that work generically over option-types, error-able types, lists, functions, tuples, etc.

In Rust, you have to specifically implement functionality for all of these.

But eg your 'map' function in Rust still works for all lists, no matter what item type. In Go before this change, you had to write a different map function for each item type that could be in your list.

In Haskell, the same 'map' function works for lists, functions, error-able types etc.

Re:Go Replaces Interface{} with 'Any' by johnisgood on Tuesday December 14, 2021 @08:37PM (#29560933)
Huge no to anything that will require .unwrap() noise everywhere in the codebase. I use Erlang, my code does not have ".unwrap().unwrap()"[1] anywhere.

[1] https://github.com/SeaQL/sea-orm/blob/64c54f8ad603df0c1d9da8...

Re:Go Replaces Interface{} with 'Any' by eru on Tuesday December 14, 2021 @11:50PM (#29562237)
That's actually a problem in Erlang.

In Haskell, 'Maybe (Maybe Int)' is a different type from 'Maybe Int'.

That means that when you use eg a hash table that returns some kind null value like 'Nothing' on lookup when a key is not found, you can still stick exactly that kind of null value as a normal value into the table and everything will turn out fine.

Re:Go Replaces Interface{} with 'Any' by TheDong on Tuesday December 14, 2021 @10:22PM (#29561693)
The comparison here is with go.

Unwrap would look like:

    file := os.Open("foo").Unwrap()
I'll take that over the current go state of the art:

    file, err := os.Open("foo")
    if err != nil {
        panic(err)
    }
Just like "panic(err)" is used infrequently, "unwrap" would be used infrequently. They're comparable, and for the cases where unwrap is okay (test code, once-off scripts, etc), I'd definitely prefer it to the panic boilerplate.
Re:Go Replaces Interface{} with 'Any' by tptacek on Tuesday December 14, 2021 @11:08PM (#29561977)
I don't understand this example at all. A Rust programmer would essentially never use unwrap on the return from File::open. It would be like checking open(2) with assert() in C.
Re:Go Replaces Interface{} with 'Any' by preseinger on Wednesday December 15, 2021 @02:43AM (#29563120)
That Go would never pass code review unless it is part of a tiny CLI tool or script.
Re:Go Replaces Interface{} with 'Any' by imron on Tuesday December 14, 2021 @09:37PM (#29561396)
I use rust and my code does not have .unwrap() (and definitely not .unwrap().unwrap()) in it either. That's what the ? operator is for.
Re:Go Replaces Interface{} with 'Any' by eru on Tuesday December 14, 2021 @11:51PM (#29562247)
The '?' is not a conceptual advance over .unwrap(), it's "just" a major syntactic convenience.
Re:Go Replaces Interface{} with 'Any' by ComputerGuru on Wednesday December 15, 2021 @02:10AM (#29562947)
Of course it is. Unwrap panics on error, while ? bubbles up the error instead. But ? wasn’t introduced to replace unwrap, unwrap was always frowned upon. It instead replaces match and return.
Re:Go Replaces Interface{} with 'Any' by imron on Wednesday December 15, 2021 @04:17AM (#29563662)
It was always frowned upon, but still ended up everywhere (including lots of documentation and example code) because it was less verbose than the match handling. The ? helped remove that last obstacle.
Re:Go Replaces Interface{} with 'Any' by kbd on Tuesday December 14, 2021 @05:14PM (#29558798)
> because eventually you have to do...

Emphasis on eventually instead of at every single function call.

Re:Go Replaces Interface{} with 'Any' by valenterry on Tuesday December 14, 2021 @10:04PM (#29561577)
> but eventually you always have to take out the value

No. You can just feed it to the function (from a library / stdlib) that needs it, or call .fold() in the end.

Re:Go Replaces Interface{} with 'Any' by peoplefromibiza on Tuesday December 14, 2021 @05:34PM (#29559055)
you can map on ok which is an alias for map_ok and then map_err for errors and or_else or_throw etc.

that's similar to what Java does with the Optional type, not great, but not bad either

the alternative is checking for nulls which is worse in any possibile way

I usually implement something like Kotlin Result when I have to code in Java

with a couple of static helpers to build the result: Result.success(T) Result.failure(Throwable t)

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-result/

also Result in Rust has been an inspiration

https://doc.rust-lang.org/std/result/enum.Result.html

Re:Go Replaces Interface{} with 'Any' by linkdd on Tuesday December 14, 2021 @06:13PM (#29559474)
I also made a library for working with `{:ok, value}` and `{:error, reason}` in Elixir: https://github.com/linkdd/rustic_result

Thanks to the pipeline operator and pattern matching, it makes pretty easy to read pipelines. It does not completely replace the with statement (that was not the point) but it simplified a lot of code.

Re:Go Replaces Interface{} with 'Any' by peoplefromibiza on Tuesday December 14, 2021 @06:42PM (#29559752)
this is nice, especially for the function clauses

Elixir is my daily drive and working in Java made me miserable until I started working around the lack of pattern matching facilities

Error handling is the worst part, I think a simple

  switch (retval) {
    Ok(val):
       ...
       break;
    Error(err):
       ...
would make Java much more pleasant, even without full pattern matching everywhere.
Re:Go Replaces Interface{} with 'Any' by crdrost on Tuesday December 14, 2021 @10:25PM (#29561711)
This sorta exists in Java 17:

    sealed interface Result<T> 
        permits Ok, Error {}
    record Ok<T>(value: T) implements Result<T> {}
    record Error<T>(error: Throwable) implements Result<T> {}
    
    // to consume
    switch (result) {
      case Error e -> e.error().getMessage(),
      case Ok v -> v.value().toString()
    }
Re:Go Replaces Interface{} with 'Any' by kaba0 on Tuesday December 14, 2021 @08:01PM (#29560577)
Nitpick, but I like to point out that Java’s exceptions are themselves a Result type/analog with them. You can unwrap it by a try catch, and can choose to rethrow it with minimal syntax. It even has a plus, it will auto-attach a stacktrace to the error case.
Re:Go Replaces Interface{} with 'Any' by absove on Wednesday December 15, 2021 @06:02AM (#29564307)
Not so much a nitpick because with checked exceptions your method signature can declare multiple types of exception whereas Result generalizes your specific exceptions to Throwable, which you can't pattern match with the compiler being able to enforce exhaustiveness.

So to achieve the same exhaustiveness as a method like

User createUser() throws IOException, BusinessException

you would need both a Result-like construct and union types

Either<User, IOException | BusinessException> createuser()

which few mainstream languages offer. Otherwise you type is unable to express that only IOException and BusinessException are thrown and you don't need to handle a default Throwable case.

Re:Go Replaces Interface{} with 'Any' by peoplefromibiza on Wednesday December 15, 2021 @08:00AM (#29565331)
checked exceptions don't integrate very well with streams and reactive pipelines, to the point that basically all of then end up being wrapped and rethrown as unchecked

methods that declare checked exception can throw RuntimeException(s) so exhaustiveness cannot be totally enforced anyway

Re:Go Replaces Interface{} with 'Any' by saghm on Wednesday December 15, 2021 @01:37AM (#29562810)
This is only the case for "checked" exceptions though; the important part about the Result type in Rust is that it won't implicitly propagate errors if you try to just use the success value but instead will give a compiler error. I don't code much Java, but my impression is that standard library methods throwing unchecked exceptions is far more common than panicking, the closest equivalent is in Rust.