673 points · by ainar-g · 6y ago · 664 comments
func (c Container(T)) Map(transform(type V)(T) V) Container(V)
if you want to see what `Result(T)` and `Option(T)` look like under this proposal, check out a very stupid implementation here https://go2goplay.golang.org/p/dYth-AQ0Fru It's definitely more annoying.But, as per https://go.googlesource.com/proposal/+/refs/heads/master/des... it looks like maybe they will allow additional type parameters in methods, which would be REALLY nice.
I think it's interesting to observe that using the Result type is really not that much different from using a multiple return value - it's actually worse in some ways because you end up using "Unwrap" which can panic.
Agreed that multiple return is actually quite nice in many situations, although `Unwrap()` is generally only called after checking `OK()` and the real benefit is in using `Map()`.
a, err := DoCalculation()
if err != nil {
return err;
}
b, err := Transform(a)
if err != nil {
return err;
}
is a lot more verbose and harder to read than a := DoCalculation()
b := ResultMap(a, Transform)I've written a decent amount of code professionally in the first and second styles.
I sincerely prefer the second style, for reasons that are hard to articulate, maybe the aesthetic, the space, or something that I assume is equally as questionable.
After I stopped writing a lot of code, when I got pulled back in to debug or provide context long after the fact, in both cases, it was way easier in "real" code bases, to catch myself back up on things in the case that the code was of style 1, than when it was of style 2!
I may be alone in this sentiment, and I even regret that I have it.
I think there is also a bit of satisfaction in writing the code in the second example, especially when the example is a lot more complex than the one provided here.
Maybe it comes down to how much re-reading/maintenance your codebase actually needs. I wonder if coding convention/style has been mapped to the types of problems that code creates and the subsequent repair of those problems being dependent on the code style... I'm sure if I google it I'll find something :)
I think type parameters of methods will definitely get added since it's so standard and if anything more confusing to not have them.
One reason I like go is it doesn't have all the bells and whistles that give too many choices.
struct Data {
idx: usize
// ...
}
struct Foo {
stuff: Vec<Vec<Data>>
}
struct Bar {
stuff: Vec<Data>
}
fn flatten_and_sort (foo:Foo, bar:Bar) -> Vec<Data> {
let mut output =
foo.stuff.into_iter()
.flat_map(|v| v.into_iter())
.chain(bar.stuff.into_iter())
.collect::<Vec<_>>();
output.sort_by(|lhs, rhs| lhs.idx.cmp(&rhs.idx));
output
}
Now you could argue that this is just "generics for collections" but the way those iterator combinators are written make heavy use of generics/traits that aren't immediately applicable for collections. Those same combinator techniques can be applied to a whole host of other abstractions that allow for that kind of user code, but it's only possible if the type system empowers library authors to do it. let mut output: Vec<_> =
foo.stuff.into_iter()
.flat_map(|v| v)
.chain(bar.stuff)
.collect(); let mut output: Vec<_> =
foo.stuff.into_iter()
.flatten()
.chain(bar.stuff)
.collect();
I might make it slightly more clear what the intent is by doing this: let mut output: Vec<_> =
Iterator::chain(foo.stuff.into_iter().flatten(), bar.stuff)
.collect();
But still basically the same.I definitely don't use generics if they can be avoided, and I think preemptive use of genericity "just in case" can lead to the situation you describe. If I'm not sure I'll really need generics I just start writing my code without them and refactor later on if I find that I actually need them.
But even if you only really care about generics for collections, that's still a massive use case. There's a wealth of custom and optimized collections implemented in third party crates in Rust. Generics make these third-party collections as easy and clean to use as first party ones (which are usually themselves implemented in pure Rust, with hardly any compiler magic). Being easily able to implement a generic Atomic type, a generic Mutex type etc... without compiler magic is pretty damn useful IMO.
class Result<T>
{
bool IsSuccess {get; set;}
string Message {get; set;}
T Data {get; set;}
}
On many occasions, I like using result types for defining a standard response for calls. It's typed and success / fail can be handled as a cross-cutting concern.It's also incredibly unsafe and why generics aren't enough. C++, Java, and so on have had generics for ages and with types like the one above, null pointer exceptions are incredibly common. Nothing prevents the user from attempting to retrieve the data without first retrieving the success status.
On the other hand, this improves on it dramatically:
enum Result<T, E> {
Success(T),
Failure(E)
}uh, you'd never get a null-pointer exception in C++ given the type that OP mentioned. Value types in C++ cannot be null (and most things are value types by a large margin).
Then chances are so are most if not all of the uses of generics OP criticises. The only "non-container" generics I can think of is session types where the generic parameter represents a statically checked state.
That it's mutable, at the very least!
Or we can learn to read them. Just treat types like a first class value. You either assign names to types like you do to values, or you can assign a name to a function that returns a type, this being generics.
That's an awful way to think about hard to read code. I could produce the most unreadable one liners you've ever seen in your life. We should condemn that and not blame it on others to "learn how to read".
Most of the time I hear about "hard to read code" is "pattern I don't currently have a mental model for". We didn't move on from COBOL by letting that be a deterrant.
Think about the audience when you code.
What about algorithms (sorts, folds, etc) on those containers? I write a lot of numerical code. It sucks to do multiple maintenance for functions that work on arrays of floats, doubles, complex floats, and complex doubles. Templates/Generics are a huge win for me here. Some functions work nicely on integer types too.
For example, what if PHP could somehow detect string-concatenation in SQL queries and instantly `die()` with a beginner-friendly error message explaining to use query parameterisation from the very beginning: tens of billions of dollars of PHP SQL injection vulnerabilities simply never would have happened - and people who were already writing database queries with string-concatenation in VB and Java who gave PHP a try would then be forced to learn about the benefits of parameterisation and they'd then take that improved practice back to their VB and Java projects - a significant net worldwide improvement in code-quality!
[1]: https://blog.codinghorror.com/falling-into-the-pit-of-succes...
I've been writing in TypeScript for about 5 years now - and I'm in-love with its algebraic type system and whenever I switch back to C#/.NET projects it's made me push the limits of what we can do with .NET's type system just so I can have (or at least emulate as closely as possible) the features of TypeScript's type system.
(As for generics - I've wondered "what if every method/function was "generic" insofar as any method's call-site could redefine that method's parameter types and return types? Of course then it comes down to the "structural vs. nominative typing" war... but I'd rather be fighting for a hybrid of the two rather than trying to work-around an poorly-expressive type system.
For enterprise-level programming (which is the environment Go grew up in), a language that's too flexible is a hindrance, because you can always pay for more eng-hours, but you can't necessarily afford smarter programmers.
Ex.
class ID<T> {
int id;
}
The idea is that an ID is just an int under the hood, but ID<User> and ID<Post> are different types so you can’t accidentally pass in a user id where a post is is expected.Now, this is just a simple example that probably won’t catch too many bugs, but you can do more useful things like have a phantom parameter to represent if the data is sanitized, and then make sure that only sanitized strings are displayed.
// UserID and PostID are distinct types
type UserID int
type PostID intIt still provides a documentation benefit of course.
EDIT: Whoops, yes, as lentil points out, they are indeed distinct types not aliases. So it does provide the benefit of the Rust solution.
I think the generic approach is a little bit better because of the flexibility, but this approach is still better than not having it at all.
For instance, if you have a function `f : Vec<a> -> SomeType`, the fact that `a` is a type variable and not a concrete type gives you a lot of information about `f` for free: namely that it will not use any properties of the type `a`, it cannot inspect values of that type at all. So essentially you already know, without even glancing at the implementation, that `f` can only inspect the structure of the vector, not its contents.
I agree with the sentiment that it is very easy to overuse genetics though there are scenarios where they are very useful.
- Promises
- Mutexes like Rust's Mutex<T> (would be much nicer than sync.Mutex)
- swap functions, like swap(pointer to T, pointer to T)
- combinators and other higher-order functions
In typescript I don't need generic too much / too complex, because the typing definition is more lax, and we can use dynamic in the very complex scenario.
I don't know which approach go is taking.
But I also have seen the problem with overuse of generics and other "advanced" type system features first hand (in libraries but also done by myself before I knew better).
s -> (s, a) is generic and a Functor (mappable - often conflated with a collection) but it's no collection!
While I think I get the reasons for these decision in theory, make a simple-to-fully-understand language that compiles blazingly fast, I still feel it's a pity (most) these issues where not addressed.
1. People will eventually want generics 2. Retrofitting generics onto an existing language is hard and leads to unusual problems
(edit: I'm glad Go is doing this, but...Java learned this in 2004.)
If you see "unusual problems" with the design, then tell us what they are.
Otherwise it's just shallow pattern matching "Java added generics late, they had problems, Go added generics late therefore they'll have problems too".
Counterexample: C# added generics late and it's perfectly fine design.
The reason Go team is not rushing to implement generics is precisely so that the design makes sense, in the context of Go.
Over the years Ian Taylor wrote several designs for generics, all of which were found to not be good enough.
They are doing it the right way: not shipping until they have a good design and they didn't have good design when Go launched.
1. https://arxiv.org/abs/2005.11710 2. https://news.ycombinator.com/item?id=23368453
We all called this when Go was created, too.
You could say that one could maybe copy the time-proven OCaml. But OCaml doesn't have a proven concurrency story, unlike Oberon and Modula-2 (yes, it had working coroutines back in 1992).
I also wish all these design decisions would not have been made in a new language, like they haven't been made in Rust. Unfortunately, the constraints under which creators of Go operated likely did not allow for such a luxury. As a result, Go is a language with first-class concurrency which one can get a grip of in a weekend, quick to market, and fast to compile. Most "better" languages, like Rust, OCaml, or Haskell, don't have most of these qualities. Go just fills a different segment, and there's a lot of demand in that segment.
Which is a mess. Sending mutable objects over channels is anything but "proven concurrency story".
Both Rust and Haskell (and OCaml, if we talk about concurrency and not parallelism) have way better concurrency story than Go. I don't care how fast one could start to write concurrent and parallel code if this code is error prone.
The only difference between Rust/Haskell and Go is that the former force you to learn how to write the correct code, while the latter hides the rocks under the water, letting you hit them in production.
That's an overstatement.
Also implicit nulls are not beneficent to anyone. And sum types could have made results (error/success) so much nicer. I see no reason to go with nulls at Go's inception, hence I call it a mistake.
Generics and Compile-Time in Rust
https://news.ycombinator.com/item?id=23534974
It's easy for spectators / bystanders to call something a mistake because you don't understand the tradeoffs. Try designing and implementing a language and you'll see the tradeoffs more clearly.
The overlooked thing is rustc produces poor quality LLVM IR which is also mentioned in FAQ.
And generics reduce amount of manual for loop juggling code one has to write. I don't think adding generics makes much of a difference.
LLVM is also slow in general. If you use it, it's likely the thing that's bottlenecking your language's compile-time unless you've done something insane like templates and `#include`, etc..
Inevitably it's the case that even if your source language doesn't do nearly as badly at the design stage when it comes to generics as C++ does, if you use LLVM your build stage is probably going to be unacceptably slow.
Go clearly values "simple and practical" over "elegant". It seems to be quite successful at that.
Not having generics and neither having very common tools doesn't seem very good. You will have to write a for loop for what is a simple function call in python or javascript or <insert modern language here>. Such detail easily interrupts reading / writing flow.
Seems you are of the opinion if you do not find something practical no one else can.
> lack of proper sum types (C, C++, Java, JS)
Incidentally, Java and C# have addressed (or are in the process of addressing) both issues. Both languages/platforms are superior to golang in almost every conceivable way.
It's been a WIP for years. Lets judge based on status quo rather than being disingenious.
I'm assuming you're talking about goroutines aka virtual threads/fibers whatever which are entirely different from actual threads.
I think that most of the standard language features are based on generics, but you would never know it, as a user of those features.
I like Swift a lot, for many reasons, but generics design isn't one of these reasons.
Swift is sort of "generics for the masses." C++ is a lot more powerful, but also a lot more "in your face." I really do like the way that Swift allows generics to have implicit types.
var v chan int
Somewhat surprisingly, the new generic types use a different syntax: var v Vector(int)
Do you now write v := Vector(int)
or v := make(Vector(int))
Not sure. The built-in generics now seem more special than they need to be. This is how languages acquire cruft.The solution to parameterized types which reference built-in operators is similarly minimal. You can't define the built in operators for new types. That's probably a good thing. Operator overloading for non-mathematical purposes seldom ends well.
They stopped before the template system became Turing-complete (I think) which prevents people from getting carried away and trying to write programs that run at compile time.
Overall, code written with this should be readable. C++ templates have reached the "you are not supposed to understand this" point. Don't need to go there again.
v := Vector(int){}
Or v := make(Vector(int))
Just like with unparameterized types.For the same reason, I dislike `std::array<T, 5>` which puts the range type before the domain constraint. This is inconsistent with `std::map<int, T>` which puts the domain type before the range type, and `[](int x) -> T` which puts the domain type before the range type.
And yeah, operator overloading leads to utterly illegible code. Let's not go there!
In Go, a pointer's integer value may not be stable since the GC may move the underlying data. This doesn't happen with today's runtime, but it may in the future.
Why does this matter? What if I want to make a hash table with the key being a pointer? The built-in map can just go ahead and hash the pointer itself (i.e. a 32/64-bit integer) since it's a part of the runtime and will be updated if the GC is changed. But a user map cannot do this: it would have to hash the actual value itself. Depending on your data, this could be significantly more expensive.
This doesn't stop anyone from implementing a hash table, but it may mean that it can't be as fast as the built-in map.
I'm not without concerns, but I'm struck by conflicting thoughts: I share the worry that implementing generics will negatively affect Go program readability which Go developers (rightfully) covet; when you have a hammer, everything looks like a nail. And yet, I also worry that the Go community is at risk of analysis paralysis on iterating the language in meaningful ways; the novel and innovative spirit that created Go must be harnessed to propel it into the future, lest it dies on the vine.
Old:
sum := 0
for _, x := range xs {
sum += xs
}
New: slices.Reduce(xs, 0, func(i, j int) int {
return i + j
})Reversing a slice of T. Copy and pasting this:
for i := len(a)/2 - 1; i >= 0; i-- {
opp := len(a) - 1 - i
a[i], a[opp] = a[opp], a[i]
}
New: reverse(a)
Or generic versions of these: https://gobyexample.com/collection-functionsI think the other replies to your comment point out the improvements that non-reduce-based versions of the code would bring, but I wanted to specifically call out reduce as being a pretty awkward function in other languages as well. So I think it's not a strong argument against generics (and the OP didn't mention wanting it in the first place); by and large functional methods like map, filter, reverse, etc are more readable; reduce is the exception that often isn't.
I wrote a fair bit of production Go code in my past, and missed many functional programming patterns. Didn't really miss reduce though. I'm glad that it seems like the ones I missed will become possible with this generics proposal.
And reduce isn't horribly unreadable, it's just a slight degradation compared to a for loop IMO. And the other functions are a large improvement.
slices.Sum() type Null(type T) struct {
Val T
Valid bool // Valid is true if Val is not NULL
}
Here's what it looks like in practice: https://go2goplay.golang.org/p/Qj8MqYWWAc3 func Make(type T)(v T) Null(T) {
}
looks really confusing and unreadable to me - too many brackets...My only negative reaction is that throughout these proposals, I've not been a fan of the additional parentheses needed for this syntax. I can think of several syntaxes that would be more readable, potentially at the expense of verbosity.
I think that there are benefits when taking the time to gather feedback from people who actually use the language and make educated decisions with regards to language features instead of shoving them down in v1.
https://go.googlesource.com/proposal/+/refs/heads/master/des...
I think that’s an unfortunate choice. Quite a few other languages use the term equatable for that, and have comparable for types that have =, ≤ and similar defined. Using comparable here closes the door for adding that later.
I also find it unfortunate that they chose
type SignedInteger interface {
type int, int8, int16, int32, int64
}
as that means other libraries cannot extend the set of types satisfying the constraint.One couldn’t, for example, have one’s biginteger class reuse a generic gcd or lcm function.
The design draft refers to “constraints.Ordered”, so they’re definitely thinking about having both “comparable” and “constraints.Ordered”. Although, for consistency with “comparable”, I think it should be called “constraints.Orderable”.
The `strings.Compare`[1] function is used to establish ordering, in the spec sense. You'd think they would name it "Order".
Similarly, the popular go-cmp[2] library provides `Equal` for equality, instead of `Compare`.
[1]: https://godoc.org/strings#Compare [2]: https://github.com/google/go-cmp
I can't find the actual code review for this. It seems to be hidden/private still?
This was the previous code review: https://go-review.googlesource.com/c/go/+/187317
The comment at the end is where I got the link to the new branch, but as an outsider, I don't have any good way to ask where the new code review is, so I'm leaving this comment here in hopes that a googler will see it and point me in the right direction.
Based on a link that's on the new branch's page, it might be CL 771577, but it says I don't have permission to view it, so I'm not sure.
The dev.go2go branch will not be merged into the main Go development tree. The branch exists mainly to support the translation tool, which is for experimenting with. Any work that flows into the main Go development will go through the code review process as usual.
Think about how much planning and foresight goes into making a programming language, especially one that comes out of a massive top-tier tech company like Google. They deliberately chose not to include generics and (from what I remember when I wrote Go code) spent time + effort explaining away the need for them. Now the decision is being reversed, and it signals to me that they don't know what they're doing with the language, long term. As a developer, why do I want to hitch my carts to a language whose core visions are very clearly not correct or what people want?
If it's so damn obvious/you're so brilliant where's your proposal dated Jun 2010 (your 'decade lost') that "solves" generics?
It may not be surprising to everyone. Trouble is that the people who are not surprised now are the ones who sat back and only watched, preventing their knowledge from making it to the project.
Luckily for Go, a small team of domain experts decided to do more than sit back and their efforts are how the latest proposal was reached.
"Generics may well be added at some point. We don't feel an urgency for them, although we understand some programmers do."
...
"Generics are convenient but they come at a cost in complexity in the type system and run-time. We haven't yet found a design that gives value proportionate to the complexity, although we continue to think about it."
...
"The topic remains open"
They haven't flip-flopped whatsoever. Now that the language has more thoroughly been fleshed out and community has matured, and various proposals have come and gone, the discussion continues.
Languages that want libraries that go ten layers deep need to carefully manage things with sophisticated type systems and compilers that can cut through and inline all the abstractions so it still runs fast. Think rust, C++, haskell (all of which, not by coincidence, have long compile times).
Languages for writing applications and solving problems tend to have a flatter dependency tree and wider standard library (often including practical functionality like JSON parsers). Think erlang, Perl, PHP.
I used to think Go was in the latter category, but it seems to be getting pulled into the former category. Perhaps that's a reflection of Go developers using more layers of abstraction than they have in the past?
I don't think Go developers are using more layers of abstraction than they have in the past; they aren't smarter or more sophisticated than they were before -- RAFT was written in Go, for example.
Your observation is a good one, however; are there other ways that Go idiomatically flattens type hierarchies?
To be clear, I was not suggesting that more layers of abstraction reflect more sophisticated developers. Just that more layers require something in the language to help developers manage those layers without going insane.
There's a lot of wisdom in choosing a flatter approach when it makes sense.
Alternatively, use the bool values and rely on the zero value for missing elements: https://go2goplay.golang.org/p/E7yHQqAPseG
However not to be just negative, I will certainly take the opportunity to provide my positive feedback as well, so looking forward to play with go2go.
Despite Go's success over the last 10+ years, have its designers concluded that the language is too simple? Is there no place for a simple statically-typed language like current versions of Go?
If not, then for those of us who particularly want a simple language, is dynamic typing the only option?
func Keys(type K comparable, V interface{})(m map[K]V) []K {
r := make([]K, 0, len(m))
for k := range m {
r = append(r, k)
}
return r
}
Usage: m := map[int]int{1:2, 2:4}
k := maps.Keys(m)
// Now k is either []int{1, 2} or []int{2, 1}.So, that's an interesting thing.
s := []int{1, 2, 3}
floats := slices.Map(s, func(i int) float64 { return float64(i) })
Type inference for generic function arguments
This is a feature we are not suggesting now, but could consider for later versions of the language.Every developer who discovers generics has this urge to be clever and write things that are hard to read and maintain.
Reading a Go codebase on the other hand is really a pleasure, this is due to the simplicity and straight-to-the-point aspect of the language, as well as the compile times. I really think Go had found a no-bullshit niche that it catered really well to, and I'm scared of what Go post-generics will look like.
Are there any other languages like Go that have no plans to move to generics?
PS: beautiful quote from rob pike: https://news.ycombinator.com/item?id=6821389
That's really unfortunate. I think a lot of the point of science (maybe even the entire point?) is to model the world and create taxonomies. Instead of being considered "busy work" or tedious, it should be held in the highest regard. Similar reasoning is why I think Rob Pike's opinion on generics is exactly wrong.
Go was already an oddball in not having generics when it came out, so I think it's unlikely that any new statically typed language will ever become popular. They're just too useful.
So instead of
func Print(type T)(s []T) { for _, v := range s { fmt.Print(v) } }
we would get
func Print<T>(s []T) { for _, v := range s { fmt.Print(v) } }
?
Foo<Bar>
You still don’t know whether this is a bunch of comparisons or a parametric type, meaning you need either feedback from the type checker into the parser or possibly unbounded lookahead before you can even generate a parse tree.https://go.googlesource.com/proposal/+/refs/heads/master/des...
Without generics, Go does not have a strong type system. It has a type system that verifies just enough to force you to work around it to do things that require generics, meaning that you don't get the benefits of verification because you've worked around it. You get the development speed of a statically-typed language with the type guarantees of a weakly-typed language: the worst of both worlds.
Gonum is good, but it can feel like a lot of the powerful abstractions in numpy and Eigen are difficult to replicate.
Whilst numpy and Eigen do "turn the magic up to 11" just a bit too much for my liking, I do like the idea of things like this:
interface Scalar() {
type float float32 int int32 int64
}
type DenseMatrix(type T Scalar) [][]T
func Identity(type T Scalar)(int size) DenseMatrix(T)
etc.Seems like the go authors are still bent on the idea that generics are really not necessarily and that there is no such problem that can only be solved by generics. Then is the generic drafting only a thing because they have been pressured into it by the community? I wonder why Rob Pike one day decided that it’s okay to change a language he almost vowed to never change after the initial release.
> Methods may not take additional type arguments
While I can fathom the complications that arise, I'm hoping they can work past this restriction by launch.
- It gets you really garbage error messages, because the type errors are usually about something in the body of the template, wherever it tries to do something that the type you substituted doesn't support, rather at the offending call site.
- It hurts compile times (above and beyond proper generics), since you need to type check the generic function at every call site, rather than just once.
- It makes it easy to break interfaces, because exactly what is required of a type parameter isn't written down anywhere -- it's just whatever the body tries to do with it.
(Though it is also true that generics are certainly not a full substitute for macros. I would welcome some mechanism for doing codegen that didn't complicate the build system and was a bit lighter weight than what we have now).
Only early extremely non conforming compilers had macro-like template expansion.
Edit: although calling templates type level macros wouldn't be completely wrong.
Edit2: a better definition is that templates are type level functions: they take compile time values, types and other type functions and return values, types and type level functions.
The Template Haskell paper has some interesting things to say on the nature of C++ templates:
https://www.microsoft.com/en-us/research/wp-content/uploads/...
Unless you mean preprocessor macros in which case I'd rather cut myself.
What is he up to nowadays?
https://evrone.com/rob-pike-interview
> Rob: Although it's far from certain, after over a decade of work it looks like a design for parametric polymorphism, what is colloquially but misleadingly called generics, is coming in the next year or two. It was a very hard problem to find a design that works within the existing language and feels as if it belongs, but Ian Taylor invested a phenomenal amount of energy into the problem and it looks like the answer is now in reach.
Sounds like he took a welcomed step back. Hopefully the new leaders can deliver.
I'm rather excited..
type Enumerator(type T) func(yield func(element T))
and the "Select" method can be written as func (loop Enumerator(T)) Select(f func(T) T) Enumerator(T) {
return func(yield func(T)) {
loop(func(element T) {
value := f(element)
yield(value)
})
}
}
You can call this method with type-safety as follows. Yay! func main() {
squares := Range(1, 3).Select(func(x int) int { return x * x })
squares(func(num int) {
fmt.Println(num)
})
}
// Output:
// 1
// 4
// 9
See https://go2goplay.golang.org/p/b0ugT68QAy2 for the complete code.And, for generality, you should write the method actually as follows.
func (loop Enumerator(T)) Select(type R)(f func(T) R) Enumerator(R) {
return func(yield func(R)) {
loop(func(element T) {
value := f(element)
yield(value)
})
}
}
However, you will get the error message then: type checking failed for main
prog.go2:17:33: methods cannot have type parameters
According to https://go.googlesource.com/proposal/+/refs/heads/master/des... this seems an intended restriction:> Although methods of a generic type may use the type's parameters, methods may not themselves have additional type parameters. Where it would be useful to add type arguments to a method, people will have to write a suitably parameterized top-level function.
> This is not a fundamental restriction but it complicates the language specification and the implementation.
For now, we have to write it as https://go2goplay.golang.org/p/mGOx3SWiFXq and I feel it rather inelegant. Good grief
This language is such a frustrating mess at times.
To anyone who has followed the Go development process at all, this proposal will not be a surprise. The previous proposal was also extremely conservative. Personally, I don't see any other way. Going full-blown generics in the style of Rust/Haskell/OCaml, for example, would drastically alter the language.
This is closer in scope to, say, Modula-3.
That said, the only feature I'd steal from Rust is sum types and getting rid of null. `nil` interfaces are the only language feature to actually cost me money and Option<T> is just better in every aspect, and Result<T> is much better than err == nil. I'd be perfectly happy with compiler blessed Option and Result types even if the larger language didn't support generics.
The type system may not always help you get your code out the door faster, but when you finally ship it, you have much easier time running it.
I have spent a lot of time in Rust getting carried away with type system stuff that is not required for the actual program I am writing. I realize this when I go over it a second time and reduce line counts drastically by replacing my gee-whiz generics with primitive types. This is balanced out by an equal number of times where I've reduced line counts drastically by using the advanced type stuff to reduce the repetition that comes along with using primitives to represent a type that has way more structure than the primitive.
I write a lot of Rust nowadays, so I often need to keep myself in check and make sure I'm not getting sidetracked. When I'm writing internal code, the priority is to just get it done but still avoiding shortcuts. This is mainly avoiding .unwrap() / .clone() / taking care to handle Result correctly, as well as regularly running clippy to pick up the obviously silly stuff.
I find the most painful part of this strategy is when you want to revisit completed code to reduce copying as that generally requires a lot of type changes. At least when you get to this point though and haven't taken shortcuts, you've got functioning software and it should be fairly fault tolerant.
In C/C++, the base type system is so weak and squishy that everything redefines every type. You can no longer pass an 'int', but instead pass a "FOO_INT" or a "BARLONG" where FOO and BAR are trivial libraries that shouldn't need to redefine the concept of an integer.
Like C#, Rust has well-defined basic types, which eliminates a crazy amount of boilerplate and redefining the basics.
In general I lean towards it not being a waste. That's not to say it's always useful for that project but it is usually useful as a learning exercise, that allows me to better identify similar patterns later (including whether generics are worth using compared to primitive types, in situations like that).
For example, I spent a good year or two forcing all of my iteration into functional styles. Now I am much better at coding in that style... and at knowing when a for loop is the more appropriate tool.
I do this too, but I’ve also come to realize that fresh perspectives and newly learned patterns may be more of the reason than being a little over zealous.
Edit: forgot to mention that this happens to me in most languages, not just rust.
In Go I never felt that omg it misses some big features we're screwed, we're going to pay the cost of running that in Prod. All the services I worked on while not being perfect ran like a clock without issues on the long term, and it has to do with Go "simplicity", eventhough you never wrote the code you can actually jump into any code base without issues, there is no weird abstraction layer / complexity that takes you day to understand.
For me the fact that Go is a "simple" language is very powerful because on the long run it's much easier to maintain.
I like Rust a lot and I hope to get to use it more, but "added type safety at the expense of iteration velocity" is not a good tradeoff for my domain and I suspect many others (although its iteration velocity is improving monotonically!).
It takes a while for something to settle down enough to say this version is going to be the code for the long run.
At that point, solidity in testing and gradual typing can be added, usually starting with the public interface.
Languages where I’ve had to satisfy all type errors in the various fragments of half brained code I’ve written for version 0.0.85 have always felt a little cumbersome. The compiler’s type checker is a perfectionist looking over my shoulder.
(Go is one of those languages. Ruby is not.)
Refactoring any dynamically typed application (regardless of size) is a manual operation, and error prone.
But then again I rarely deal with type errors, when I do it's the compiler looking out for my often 'application ending' mistakes.
Go, the language, is simple. Hard to argue with, and sounds great.
The code I have to write though, it's quite simpler to do it in Python more often than not.
What is missing is a language with good static type system (Algebraic data types, stream/iterators, generics), simple and having GC, for application domains where prototyping speed matters.
F#, OCaml and Haskell (and other ML-family languages) satisfy the first 3 criteria (type system, simple and GC) and depending on your familiarity with the language, can be fairly suitable for fast prototyping.
For example, I write most of my new personal projects in Haskell, and I'm able to iterate pretty rapidly once I have a skeleton of the system in place (with liberal use of typed holes to ignore things I don't care about implementing right now). For some projects, I find I'm actually able to prototype more rapidly than I would be able to in an untyped language, because the language helps me express the shape of the data through algebraic data types, and then the functions end up having "one obvious implementation" that follows the structure of the data.
Mypy for Python (https://mypy.readthedocs.io/en/stable/) and Flow for Javascript (https://flow.org/en/docs/) are my personal favorites, and have all the features you describe. And importantly, both languages have very strong library support.
As for programming with types, that's partly what Go was trying to avoid: https://news.ycombinator.com/item?id=6821389 . And I agree with Pike on this one. The nice thing about Go for me is that I'm just writing code. Not defining a type hierarchy, not rewriting some things to get them just right, not defining getters, setters, move and copy constructors for every type :). Just telling the computer what to do and in what order. When I'm writing a library I'm defining an API, but that's about it; and you can usually steal whatever the standard library's patterns are there.
I disagree about nil as well; I think Go's zero value approach is useful, and basically impossible without nil (it wasn't necessary in my code, but I may want to instantiate an ApiResponse object without a data structure ready to be passed in).
A little bit of a rambly response from me, but, all in all, I think I'll be one of the stubborn ones which refuses to use generics in his code for a long time.
> Sounds like Rob Pike doesn't understand type theory.
I'd be a bit more charitable; Pike is a smart dude, I'm sure he does understand type theory, but has decided he'd prefer to write imperative code. And he's actually good at writing imperative code correctly, so for him, that works. But most people are not very good at writing imperative code correctly, at least not the first time, and not without writing a large volume of tests (usually several times as much test code as program code) to verify that imperative code.
Or perhaps Pike was just assuming the person he was talking to was only talking about types in the OOP sense. If that's the case, I agree with him: taxonomies are boring, and inheritance often leads to leaky abstractions.
But types let you do so much more than that. I much prefer being able to encode behavior and constraints into the types I define over writing a bunch of tests to verify that the constraints I've expressed in code are correct. Why do the work that a compiler can do for you, and do it much better and more reliably than you?
How are languages other than Go (like Rust, Swift etc.,) not imperative? They are nearly as much imperative as Go but have FP features like ADTs and pattern matching, but those don't make them "functional". This point might be valid if you are talking about Haskell, MLs and the likes.
> I much prefer being able to encode behavior and constraints > into the types I define over writing a bunch of tests to verify that the constraints > I've expressed in code are correct. Why do the work that a compiler can > do for you, and do it much better and more reliably than you?
IMO, this "types replacing tests" might be true when comparing dynamic vs static typing, but for already static typed languages, extra typing cannot be a substantial gain. Personally, I find type-level programming beyond a certain extent to be counter productive and it doesn't seem to have much impact on correctness (unless we bring in dependent types).
I like your solution to my imaginary problem, but I am going to counter this one. Now I'm salty because nil interface[1] actually bit me once and cost me. Go's zero value approach also exists in Rust, but is type safe. Basically every primitive type, and Option<T> have zero values. Any struct that is made up of those values can also safely have zero values. Then for those that don't, you can implement your own zero values. This is called Default in Rust. Go's zero value approach is perfectly possible, and arguable better without nil. And even then, the number of times I've seen a service crash because someone "forgot" to initialize a nullable type, and passed it to a function that then exploded isn't an issue I should deal with in 2020.
[1] https://medium.com/@glucn/golang-an-interface-holding-a-nil-...
As for your proposal, there are some issues with it: not all structures have a sane default for all not optional, nilable parameters. What is the default underlying reader for a bufio.Reader? A reader which returns zero bytes? Certainly that would be more confusing to debug than a simple panic, which is what we have now [2]. There's also the fact that a zero value is just a value with all the bytes zeroed and allocating an object via language means (new) never allocates more than the size of the object and doesn't do computation.
But I guess the main point would be that I simply do not have a problem programming with nil-able types. Failing to initialize in Go means writing var a *T as opposed to a := &T{} or a := NewT(), which seems like an odd mistake to make - or forgetting to initialize a member of a struct in the NewT() function. Fundamentally, I do not want to spend hours of my life dealing with safeguards which are protecting me from a few minutes of debugging.
But hey, that's just me. Go isn't Rust and Rust isn't Go and that's a good thing.
[1]: https://play.golang.org/p/L7iy9YBC55c [2]: https://play.golang.org/p/Vgv73KhegKI
It's designed to be simple, to be boilerplate, to be easily reviewable/checkable by coding teams.
Not sure why Go and Rust are always the compared languages. Go is designed to replace Java/RoR/Python in Enterprise-land, not to replace C/C++.
Rust is designed to replace C/C++ in system-land, embedded, kernel, thick app components (browsers are probably the most complex apps running these days on end user systems). The entire focus is zero-cost abstractions.
Rust can't cover the enterprise use-cases of Go the same way that Go won't ever cover what Rust can do on systems/embedded level but there is enough overlap in some cases to confuse people into trying to compare them directly.
I have seen average programmers who can write less dumbed down code than the most succinct code possible in Go.
I have seen below average programmers who understand how to use generic data structures / programs in C++ / Java / C# etc..
> It's designed to be simple, to be boilerplate, to be easily reviewable/checkable by coding teams.
Boilerplate and easily reviewable are at the odds. Unless Enterprise style java is the bar, it is hard for anyone to say that. Go is too much boilerplate than average programmer's python code, for example. Don't tell me python is dynamic. The average programmer doesn't do metaclass magic.
Being so much boilerplate and verbose `if err != nil` and no generics and no methods/functions for common operations like finding the index of an element in an array. All this leads to for-loop-inside-while-loop-inside-for-loop attrocities where it is harder to decipher what the intention is. Compare to python where you have methods on collections to carry out common manipulations, and list comprehension in python is so cleaner than 4 line imperative go code.
Go seems to miss why python/JS/ruby are so popular. It is because so much is built in that you can communicate __intent__ clearly without getting bogged down in details. Compared to any modern language that's not C and not mediaeval C++, Go is so much more verbose. Even java has enough shortcuts to do these common things.
And don't start telling me this leads to incomprehensible code. Coding standards are there. What's unreadable is 8 level indented imperative attrocity of blue collar language Go.
> Not sure why Go and Rust are always the compared languages.
They both emerged at same time and have some overlapping scope - eg static native compilation, memory safety etc.. but there similarities end. However, there is lack of a a popular, succinct natively compiled language which gets out of the way to write software. Everyone knows expressive languages need not be slow or difficult to deploy. Some people have to write Go in dayjob and the sibling rust, having quality-of-life improvements that anyone expects in a post-2000 language [0], seems to be a closer candidate to comparison (even though rust isn't the optimal language for the things Go is used for, given it is a systems language with static memory management) Others like D and Nim have a fraction of users. Of course there are also some vocal rust fanboys who think crab god is not popular because world is anti intellectual.
Secondly, I don't think the fact that Go making the opposite trade-offs in terms of (let's say) programmer effort vs. CPU clock cycles means it is a "language for the average". Go is great for any number of interesting high-level server-side components where it being done in half the time is better than it being 15% faster.
> to be easily reviewable/checkable by coding teams.
I strongly disagree with this. I find Go code to be incredibly difficult to read. This is because of two main reasons.
The first is that the lack of expressive power in the language means that many simple algorithms get inlined into the code instead of using an abstraction with a simple and understandable name. I find that the first pass of the code is me reading over the lines (each of which is very simple and understandable) and virtually abstracting it into what the code actually does. I find that the interesting business logic is lost in all of the boilerplate.
out := []int{}
for _, v := range input {
number, err := fetchData(v)
if err != nil {
return nil, err
}
if math.Abs(float64(number)) <= 2 {
continue
}
out = append(out, v)
}
return out
vs input.iter()
.map(|&v| fetch(v))
.filter_ok(|number| number.abs() > 2)
.collect()
As I said, every line in the Go is simple (except maybe for append, but generics can help with that). However the actual business logic is lost in the boilerplate. In the second example (Rust with one existing and available helper function) the boilerplate is much less and each line basically expresses a point in the business logic. There are really two bits of boilerplate here `filter_ok` instead of `filter` to handle the errors from `fetch` and the `collect` to turn the iterator into a collection (although maybe you could improve the code by returning an iterator instead of a collection and simplify this function in the process).Secondly the "defaults are useful" idea is in my opinion the worst mistake the language made. They repeated The Billion Dollar Mistake from C. I have seen multiple expensive production issues as a result of it and it makes code review much harder because you need to check that something wasn't uninitialized or nil. It is absolutely amazing in Rust that I don't have to worry about this for most types (depends on your exact coding style, in the above example there is never a variable that isn't "complete").
So while Go may be quick to write. I think the understandably is deceiving. Yes, I can understand every line, but understanding the program/patch as a whole becomes much more difficult because of the lack of abstraction. Humans can only hold so much in our head, making abstraction a critical tool for understandable code. So while too much of the medicine can be worse that the disease I think Go aimed - and hit - far, far below the ideal abstraction level.
> We—Ken, Robert and myself—were C++ programmers when we designed a new language to solve the problems that we thought needed to be solved for the kind of software we wrote. It seems almost paradoxical that other C++ programmers don't seem to care.
https://commandcenter.blogspot.com/2012/06/less-is-exponenti...
If I understand it correctly, your code doesn't check when unmarshalling if the content of Data has the expected structure. Using interface{} it's always been possible to achieve something like you'd do with Generics but it's ugly and can't check types at compile time.
The way I tend to look at this is the 30 minutes I spend up front making my types work will usually save me hours of time later (sometimes much later, and spread over different coding sessions), because if I'm using the type system to enforce constraints, I'm not going to have to worry about writing buggy constraint code.
When I was learning Scala (after working in Java most of the time), I noticed that I would sometimes spend quite a bit of time getting short snippets of code correct so the types would line up. The result would be shorter than the equivalent Java code. But I had much more confidence in that code actually working, without needing to write tests (or at least as many tests), because I was leaning hard on the type system to prove the code correct. You can do that to some extent in Java, but the type system there is a bit weaker, and the standard library and common idioms make it harder to do. Ultimately if I have a chunk of Java code and a chunk of Scala code that does the same thing, I'm much more confident in the Scala code because I know scalac is providing me stronger guarantees than javac, assuming I've written the code to make good use of the compiler's abilities.
Today Rust and Go exist in different spaces. Go is a Python/Ruby/Java/etc alternative. Whereas Rust is an alternative to C/C++/etc. Obviously there is overlap between those sets of languages but that doesn't really mean Rust and Go are as directly comparable as HN comments might lead people to believe.
Whereas Rust user and committers are much more interested in discussing what is good programming, nuances of PL theory and so on. It does not matter if the post is about Rust or not and specially if it is about Go.
If you start talking about changing the recipe for Coca-Cola, surely Pepsi is going to enter the discussion at some point, right?
Fitting analogy: If there's an article about McDonald's, people would always talk about Wendy's instead. No one would mention BurgerKing (C++), Subway (D), KFC, ...
To me, Go vs JVM ecosystem languages is a much more difficult choice. I would have to actually think a bit.
To me, Rust and Go really don't occupy the same ecosystem niche. I can't think of a project where I would have to choose between them--the choice between them is almost always dead obvious given the project description.
> a style of computer programming characterized by the _ritual_ inclusion of code or program structures that serve no real purpose.
I must say I am biased, since I develop a language that I believe fits the sweet spot here. I would encourage you to give it a try: https://nim-lang.org
I think I get way more friction from:
- library authors that go crazy with generics.
- the million ways rust makes performance tradeoffs explicit (even when you're writing part of the program where performance simply doesn't matter).
- the million-and-one things you can do with an option type.
- the arcane macro syntax.
I could probably go on. I've been writing a lot of rust because I wanted a low-ish level language with good C interop, and I didn't want to learn C++, so I wasn't at any point a rust fanboy. I very much appreciate not having to be a genius to avoid segmentation faults, but other than that, I think rust is a somewhat ugly language - for the simple reason that it has a lot of features, some of which partially overlap, and most of which are vaguely inconsistent.
I'm probably sounding a bit harsher than I mean to - obviously, you can't expect a language like rust to have the simplicity and consistency of something like lua, and by and large, it's better than anything else I write programs in.
Still, the point is, as somebody with a lot of (fair and unfair) complaints, the burrow checker is not one of them. It complains rarely, and when it does you're almost always doing something stupid, unless you're doing something fairly arcane, in which case, you should probably use unsafe.
Rust effectively forces you to code like you're writing a multi-threaded app even when you aren't. There's a reason why people suck at writing multi-threaded apps: because it's hard. This is what people are fighting when they fight the borrow checker. And this is why so many people find it frustrating. There's all sorts of designs that flat out don't work or are way more effort than they're worth.
C also makes you think about ownership in your API design, it's just the language doesn't give you any real tools to express or enforce it. C++ gives you a bunch of tools and options, but you have to hope that you and the API you want to use agreed on which subset of the tools to use.
Garbage collected languages specifically take memory management out of the API design by declaring that the runtime will take care of it for everyone.
If you want lifetime to be something an API can control, then I think Rust's approach makes sense even though it obviously adds complexity. If you don't, then, yes, removing it from the equation definitely lowers the API design burden.
In many ways its analogous to having language support for strings. In C/C++, you gotta hope that the library you're using has the same approach to strings that you want (std::string? char*, wchar_t?, something else?). In newer languages, it's just a given. (For better or worse: because then you end up stuck with UTF-16 in some languages.)
My vote goes towards good thing.
One of the things I like most about Rust is that it forces you to think through your design and address complex tradeoffs, and often won't even compile until you do.
What it costs you in development time, you'll make back in reduced maintenance. The former is a visible cost therefore you feel it more than the latter which is invisible when things run well.
This is why Rust can feel less productive even if it makes you more productive in the long term if you take in to account less maintenance.
I have heard this bullshit enough times. "Orange crab god doesn't like it so you are doing it wrong". No, you shouldn't have to care about memory management nuisances when that's not relevant and rust being a language suited for systems domains with correct static memory management (Good thing for systems domain), makes those irrelevant details surface in implementation.. what you said isn't true for other domains.
This kind of shilling is what leads to rust evangelism strike force memes.
In C++ you can write:
template <typename Animal>
void roar(Animal animal) { ... }
and call it like this: roar(airplane); // How do Airplanes roar?
You can try to fix that with an "Animal" concept, but it turns out that if someone adds a roar method to a Vehicle, you can still: roar(truck); // Trucks can roar... but roar expected Animal
In Rust, these things just cannot happen. If you write: fn roar(animal: impl Animal);
then trying to call it with anything that's not an animal will fail to compile.That's a good thing, but maybe somebody did wanted to call roar with a truck, and now you have to invest time into more precisely thinking which types should roar actually take, which types constraints make sense defining, how you categorize types, etc.
In Rust thinking about these things costs time. In C++ it also costs time, usually more than Rust, because you have to go way out of your way to prevent mistakes like the above. In Go you don't have to think about these issues at all because the language does not allow you to do most of this (except for interfaces, but that's another story).
I wouldn't want to spend that time one a one off script I only expect to run a few times.
I also wouldn't want to spend that time only to find that my assumptions were wrong or the requirements changed and I have to throw it all away for a new class puzzle.
You don't have to. No generics, `.clone()` and `.unwrap()` everywhere, and the Rust code goes brrrrr. :D
That said I agree completely, `Option`/`Result` themselves (even if they are just intrinsic language elements, not user-implementable types) are valuable.
I usually do stuff like this as a YAGNI exercise. Don't spend the extra 25 minutes thinking about it until you know you have 3 or so cases where you'd actually be sharing code. But at that point... the consistency you can get starts to become attractive, if you want the behavior to stay consistent in the future!
> The jury is out if thats is a good thing or a bad thing
Well said. I have this same thought with TypeScript on a frequent basis.
It includes:
- Having some understanding of how type systems tend to work and common patterns around them, preferable in a abstrac non language specific way. Do not confuse it with knowing formal CS since type theories, it's not the same.
- Knowing how to effectively use the type system to encode important variants.
But probably even more important:
- Not getting obsessed with trying "perfectly"/"optimally" use the type system.
- Knowing that the moment your types and their relations get too complex it might not be worth it at all, even if you encode use-full variants. Sometimes just having runtime checks is so much better from a API UX point of view. Getting complex type system based API's right is hard and from what I see in the open source community most people do not have the skill to do it right. (Through this doesn't mean not using the type system to encoded constraints, just not over using it!). A common case where this happens is when people try to use the type system to force a DSL into a language which isn't very compatible with that kind of DSL.
While I often see people learning about how they can use advanced features of a type system but they do not learn when to _not_ use it.
Disclaimer: I just realized that what I see as Simple usage of the type system the parent post might already see as advanced usage.
This is very real. One reason I like Rust for serious projects that deserve this level of thinking time, but I'm wary to use it for simple 'toys'. Go was far easier to jump into but also far easier to push against its limits.
Some sort of compromise might seem better here but I like using the best language for the job. Rather than some all-encompassing developer experience or language use-cases.
I think you summarize it perfectly though, my favorite parts of Rust are Option/Result.
What does get rid of errors is IDE support for nullable types which warns the programmer that they have accessed a property without checking for nulls. Take kotlin and Intellij/IDEA for instance.
IDE support is half baked, someone can always turn it off.
The way I look at it, and I could totally be wrong, is if you go for a different language for your back-end than your front-end, it betters pay off big time. I find Go and Typescript to be in a very similar ballpark in term of productivity, but with Typescript having a huge advantage since you can reuse all the learning/tooling from the front-end.
Rust on the other hand really adds something to the table with the memory safety and zero-cost abstraction.
TL&DR: It feels like either you eat the bullet and go Rust for memory safety, or Typescript is a better choice. Of course I'm overly simplifying.
Thoughts?
Go shines when you have a lot of parallelism, and not a lot of concurrency (although sync package is fantastic). Web servers, data processing pipes, task queue consumers...
Also the language is simpler. Personally I think in it like C vs C++ or RISC vs CISC.
And last, but not least: Go have faster compilation times. Rust compilation is slow, and for some tasks that requires retrying (like learning a new language) compiling fast is very valuable.
For the majority of software (I guess you are referring to web apps), simpler/GC/scripting languages like TypeScript or Go are better.
But, if you really need something low-level, then you need C, C++, Rust, Zig, etc. and there is no way around it.
You need a for loop for what is done in other languages with one method call.
Removing an element from an array doesn't look like that. It is some slice appending trickery.
Having null and having to check errors every 5th line or so..
It lacks idioms like list comprehensions or map / filter. Reading code is spent in details like whether a for loop is index(), count(), map() or filter().
Instead of some simple code like x = condition ? a : b you are writing imperative verbose code like: if condition { x = a } else { x = b }
Go maybe simpler than enterprise-style java. But that's not 'simple'.
I find it much easier on the eyes than java.
Unfortunately, I have had to deal with too much "exciting" code. So I am very happy with Go so far and this latest concept of generics seems to add the least amount of complexity for the problems it solves.
I'm pleased to see they've made this proposal even more boring and removed contracts.
i feel like i'm at a point of language overload as it is these days, I don't have the mental space for yet another language
I agree with you that I think they're slow to improve. I'm not sure if innovation is necessary though, since most people rely on the language being stable going forward.
Personally I struggle with deciding when to use Go for a new project. With so many languages now supporting different concurrency paradigms, and containers abstracting away prior deployment pain points, I'm not sure why I'd reach for Go over any of the others.