101 points · by isaacimagine · 5y ago · 71 comments
type SignedInteger interface {
~int | ~int8 | ~int16 | ~int32 | ~int64
}
Interfaces that contain type sets are only allowed to be used in generic constraints. However, a future extension might permit the use of type sets in regular interface types:> We have proposed that constraints can embed some additional elements. With this proposal, any interface type that embeds anything other than an interface type can only be used as a constraint or as an embedded element in another constraint. A natural next step would be to permit using interface types that embed any type, or that embed these new elements, as an ordinary type, not just as a constraint.
> We are not proposing that today. But the rules for type sets and methods set above describe how they would behave. Any type that is an element of the type set could be assigned to such an interface type. A value of such an interface type would permit calling any member of the corresponding method set.
> This would permit a version of what other languages call sum types or union types. It would be a Go interface type to which only specific types could be assigned. Such an interface type could still take the value nil, of course, so it would not be quite the same as a typical sum type.
> In any case, this is something to consider in a future proposal, not this one.
This along with exhaustive type switches would bring Go something close to the sum types of Rust and Swift.
interface Result[T, E] {
for Ok[T], Err[E]
}
And there’s no issue with having T=string and E=string. type Result[T any, E any] interface {
T | E
}https://golang.org/doc/go1.17: three very minor changes for array pointers and unsafe
https://golang.org/doc/go1.16: no language changes
https://golang.org/doc/go1.15: no language changes
https://golang.org/doc/go1.14: minor change to allow "overlapping interfaces"
Of course, in 1.18 -- coming out in about three months -- there's the huge change to add generics (type parameters). The best way to read about that is in the type parameters proposal here: https://go.googlesource.com/proposal/+/refs/heads/master/des...
Go 1.18 will also add built-in fuzzing support, but again, that's a tooling/library change, not a grammar/language one.
I think sum types, possibly in combination with tuples would have been nicer than multiple return values. But I guess everyone has their particular wish list of what a programming language should be :-)
The way golang ~makes me encodes it makes using these functions annoying, because then you ~need to test for the nonsense cases where you have neither an error or a result, and maybe where you have both.
"a*, error" has 4 different members, if you consider just "exists" vs "doesn't exist" for each. Of those, "nil, nil" and "&a{}, errors.New("whatever")" are broken. Fully half of the things you can represent are just wrong.
(Yes there are times when those are valid returns, but easily 99% of the time they're not. The type system should be able to represent both ways.)
This is the reason for instance in C# Hot Chocolate GraphQL library the newly proposed return type for fallible mutations is, e.g. for hypothethtical register function:
{
user: Option<User>,
errors: [Errors]
}
Instead of more type-correct way of: union result = user | Errors
Precisely because using unions is gnarly in JS who are the main consumers of the API.Similarly if GO doesn't have a way to pattern match, the actually using sum types is very annoying and this "foo*, error" can be seen as more convinient.
While sum types and union types are close, they are not exactly the same. Let's take an example:
union bools = bool | bool
enum Bools = A(bool) | B(bool)
The example is a bit weird but shows an important point: bools has 2 values, true and false. Bools has 4 values, A(true), A(false), B(true), B(false). In bools (the union), true and true is always the same. In Bools (the sum/enum), A(true) is not the same as B(true).I don't know enough about type theory to know if union types have a relationship with sum types. They can be used the same for most cases but they have differences around the edges.
I actully wrote just few days ago about how cool it would be if TypeScript-like language too had tags:
https://github.com/Ciantic/thoughts/blob/master/2021/dynamic...
Compare Rust's https://doc.rust-lang.org/std/str/fn.from_utf8.html
If you've got a buffer full of bytes, which you hope are UTF8 text but maybe aren't, call std::str::from_utf8 and you either get back a string slice with your text in it, or you get a std::str::Utf8Error structure which explains what the problem was in an actionable format. You can write code to process this Utf8Error and your bytes - maybe you're reading blocks of data and it's all valid UTF8 but the last character is continued in the next block for example, you can discern that from Utf8Error and just turn the valid part into UTF8 and keep the rest until the next block is available.
Indeed, I recently updated some code to return a relevant value in the error case: https://github.com/wal-g/wal-g/pull/1143/files#diff-d896e5d5... where true means the error is rooted in a corrupted page, & false means that the error isn't due to a corrupted page. It does feel a little dirty & a comment is probably necessary to make this case clear
Still, Result can work here. For example, Rust's binary_search https://doc.rust-lang.org/std/vec/struct.Vec.html#method.bin... which returns Ok(idx) when that's the location of the element, or Err(idx) when that's the location the element would be if it were there (this can be a bit annoying when you just want to insert, since you end up writing `let idx = match result { Ok(idx) => idx, Err(idx) => idx }`)
(I don't agree that sum types should be added to Go, as much as I dislike the language as it is)
Virgil has variants and also enums. They are slightly different things, though treated much the same under the hood. Neither have identity. (How they are different is that enums can have arguments in Virgil, but there are still is a fixed list of named values, whereas variants have named cases and are potentially recursive).
But considering the proposal itself. I would approach it much differently.
Sum types could be represented as a closed enum.
type Result enum int{…}
const ( Ok Result = iota{interface{}}, Err Result = iota{string} )
The initialization would be done like: Ok{10}
Err{“Something went wrong”}
The variable itself would act just like and other enum with unpacking being done somewhat close to this: Ok{variableName} := result
Where the variableName would be set to the zero value in case of a bad match.The enum prefix would enforce a single const block and no extension outside the module package.
You don't get a literal enumeration of all implemented types in the interface specification itself, but it's still trivial/mechanical to extract all implementations of such an interface with some code tool, and no external package can add to the list.
(Since I've learned from experience this always comes up: If you put a method named 'unexported' on your interface, it doesn't matter if a value in some other package creates a method called 'unexported', the compiler will not consider it a match. An interface in some package with an unexported method can not be implemented by any other package.)