Why Go Is Not Good
yager.io
yager.io
But, for systems programming, abstractions suck. They always, always have a cost. When abstractions break, you not only have to deal with a broken system but the broken abstraction itself too. (Anyone who has ever seen a gcc compiler error for C++ knows how this feels.)
Therein lies Go's value proposition. It does not make it possible to make things pretty (ugh, nil). It just makes it impossible (ok, really hard) to overcomplicate things. When you write Go code, you can picture what the C equivalent would look like. You want to deal with errors? Here's an if statement. Data structures? Here's a struct. Generics? Here's another if statement, put it inside your for loop.
Obviously, Go is not the right choice of language for most things. When you're doing application development, you may be able to afford the cost of abstractions. But for tools that only need to do one thing and do it extremely well, it's either that or C. And I'm not going back to managing my own memory anytime soon.
Using C++ template error messages to attack generics in Rust and Haskell is pretty weak, because typeclasses were explicitly designed to avoid the problems of "ad-hoc" templates in languages like C++. Error messages are in fact what typeclasses are really good at.
Dear God.. I dont know why so many programming languages anyway to do the same thing all over again.. just because of the sake of the sintax or the type system.. or because the guy fell sooo smart because hes using FP.. so he can fell instelectually superior to all human beings
Since C.. its all the same programming paradigm.. the rest is just detail.. the only langs that have its own way that are not cover by the C paradigm are Lisps
Really my language of dreams.. will be to use notes like in a music sheet.. this is a really different paradigm.. or use DSP with just I/O signals.. this is something new.. the rest is just vanity..
And i dont want to be the rat lab of some language designer full of himself, that doesnt think of me, the poor programmer that has to maintain the code in the lang he creates!!
This is the unix philosophy... theres too much noise, im sure these are the kind of things that make people run away from technology...
We need to somehow find our way to simplicity.. for our own sake
And the hundreds of other languages serve what purpose then ?
However I think your benchmark for a language's worth is a pretty superficial one.
Luckily it's used less, but that doesn't change it really. Anything becomes a double pointer indirect.
And just for completeness : even java has better tools for abstractions.
> But, for systems programming, abstractions suck. They always, always have a cost.
> Generics? Here's another if statement, put it inside your for loop.
If you care about speed (and many systems programmers do), this is exactly the opposite of what you want to do. Unlike your proposal of putting potentially-costly if-statements inside of for loops, generics/templates in c++ provide zero-cost abstraction (in terms of execution time. If you think dealing with the error messages presents too high cost in terms of developer-time, switch to clang).
Depending on who you are working with, the lack of generics is a blessing. Some developers can't restrain themselves and create over-complex abstractions that are used only once.
Picture this function:
foo :: (a -> b) -> (b -> c) -> (a -> c)
What does it do?As you can see this function takes 2 arguments, which appears to be functions. It also returns a function. The argument and return type of these functions are unknown, so you can't manipulate them. You can just pass them around directly. This puts really tight constraints on your code. So, assuming nothing fancy happens, there is only one correct body of code for this type signature:
foo f g = \x -> g (f x)
In other words, function composition.---
Generic functions have more guarantees than non-generic functions. Therefore, you are more likely to know what a generic function is actually doing.
This is backward. A function, polymorphic or otherwise, does not influence code that does not call it. Modulo far-reaching side effects of course.
It's when you look at the call site that you have to figure out what this strange `fold` function could possibly be about.
I'll grant that polymorphic functions are often more abstract than monomorphic ones. But they are simpler. They are also better at separating concerns. Take `map` and `filter` for instance. They capture common iteration patterns, so you don't have to entangle that pattern with the actual logic of your loop. Without parametric polymorphism, you could not write them (more precisely, you would have to repeat yourself over and over).
> A better form IMO is restricting the types allowed as it: 1. makes understanding much easier
That's just false. If you restrict the types a function can operate on, you allow the function to do more things to its data. The more you know about its input, the less you know about the function. With parametric polymorphism, you are actually hiding information from the function, preventing it from making whole classes of mistake. Free tests!
Parametric polymorphism makes functions that use it simpler (as in, less moving parts). How could that possibly be harder to understand? Please give a concrete example, I don't understand where you're coming from right now.
> 2. Doesn't create bloat in the form of n copies for visible symbols.
That's an implementation detail, and mostly false anyway. Not every language is C++. Most languages that make use of parametric polymorphism don't duplicate code.
This is exactly why c++ allows template specialization, and if you don't care for hand-optimizing, you can get both implementations almost for free.
> Depending on who you are working with, the lack of generics is a blessing. Some developers can't restrain themselves and create over-complex abstractions that are used only once.
I can't comment on the competency of your coworkers, but I certainly see how Go could be useful in situations without the kind of performance-constraints which demand a language like c++.
I'm pretty sure that's what C++ templates specialisation is for...
Generics encourage over-generalizing behavior that runs counter to writing highly performant code. If you care about speed, you don't spend time making your code generic. You optimize closely to your use case.
I think you may be missing some info regarding generics in Rust and Haskell. As I mentioned in the article, there is zero runtime overhead for generic programming in Rust and Haskell. Zip. Zilch. Nada. That's why their constraint-based static generics system is awesome.
ghci>let add3 a b c = a + b + c
==================== Simplified expression ====================
GHC.Base.returnIO
(GHC.Types.:
((\ (@ a_ayZ)
($dNum_az0 :: GHC.Num.Num a_ayZ)
(a_ayG :: a_ayZ)
(b_ayH :: a_ayZ)
(c_ayI :: a_ayZ) ->
GHC.Num.+ $dNum_az0 (GHC.Num.+ $dNum_az0 a_ayG b_ayH) c_ayI)
`cast` ...)
(GHC.Types.[]))
Compare this to the Int-specialized add3, which does not have to be passed the extra $dNum_az0 argument: ghci>let add3 a b c = a + b + c; add3 :: Int -> Int -> Int -> Int
==================== Simplified expression ====================
GHC.Base.returnIO
(GHC.Types.:
((\ (a_azj :: GHC.Types.Int)
(b_azk :: GHC.Types.Int)
(c_azl :: GHC.Types.Int) ->
GHC.Num.+
GHC.Num.$fNumInt (GHC.Num.+ GHC.Num.$fNumInt a_azj b_azk) c_azl)
`cast` ...)
(GHC.Types.[]))
Now, am I saying the the typeclass method isn't fast, or that GHC can't then optimize that Num dictionary away via specialization or inlining? No, I am not saying that. But it certainly doesn't always do that, resulting in a performance hit at runtime. More info @ http://www.haskell.org/haskellwiki/Performance/OverloadingI really hate it in Java when I need an array of bytes but don't know the size in advance, or the size changes, and I have to incur all the cost of boxing those bytes up. On 64-bit systems (most of them), pointers are 64 bits which is at least twice as large as the most common things you put in a list (int, float, byte).
You don't need to box something to make it generic.
Sure, generics don't have runtime overhead in Rust and Haskell but they have other costs. You always pay for abstractions some way.
The speed of the Rust compiler has little to do with generics and everything to do with LLVM and its optimizations and code generation. (Run with -Z time-passes if you don't believe me.)
With generics, the novice finds cases where the compiler catches them doing something wrong, so they rewrite the code using casts in a way that looks right but is subtly wrong.
The end result is code that appears correct to the novice, the novice walking away with the feeling that generics are too complicated, and a mysterious corner-case bug that bites off someone's arm once every five years.
The nature of failing to understand is that the person who fails to understand often fails to understand that they misunderstand, or often misattribute their misunderstanding. The tool gets blamed for getting in their way of writing "good" code. On the other hand, there are plenty of tools that give perfectly sensible error messages to anyone with a PhD in type theory, but a second year university student sees "Attempt to cast non-monoid endofunctor to monad. Please uninstall compiler and shave off neck beard."
Could you clarify what you mean by "systems programming"? To me, that means working with embedded systems, which Go is certainly not appropriate for.
The blunt but approximately correct version is that embedded means that you're running on hardware that isn't powerful enough to run a Linux kernel.
Systems programming just means you're working below the application layer. So if you take your laptop and write a device driver, or work on filesystem or networking code, you're doing systems programming without doing embedded.
That's a good point though. A lot of people mean different things by systems programming.
Actually, no. It meant one thing until Go proponents tried to market their language and realized that their target audience didn't actually care.
I'd also s/didn't actually care/got confused/ in your last sentence too.
Yes there are GCs for C, but is anyone successfully doing "systems programming" (whatever that may be) in C with GCs?
Actually, yes. But it's hackish (relies on some pretty complex macros) and requires you to adapt certain conventions. Still, it's doable and a whole lot safer than managing your memory directly in terms of leaks and re-use after free. The cost to me really is that macro magic, that should not be required but it's the only thing I could think of to make this work. To give you an idea of just how ugly this is I re-defined 'return'. Any C hacker will be able to deduce the rest from that one hint ;)
On another note, I felt - and feel - that this was not the proper solution but the various policy choices made this pretty much the only way in which it could be done. And it works.
-- I know, you didn't think it made any sense either. I'm just pointing out that a line has to be drawn somewhere; where it gets drawn is actually arbitrary.
Yeah, I've had to deal with ridiculous mandates from on high too, though none anywhere near that onerous. In my previous job, we were writing a compiler. It was mandated to be in C++ -- the first mistake -- and we had to use smart pointers instead of GC -- also a mistake. But the completely idiotic thing was that we were not allowed to declare any exception classes. The VP of Engineering -- a very smart and experienced but very arrogant guy -- had seen exception hierarchies get out of control before and decided the solution was to ban them.
But that's on a pretty small scale compared to what you're talking about.
Sorry, could not resist.
But like I said, if I didn't care about GC or concurrency, I'd be writing C.
Don't make GC's a bigger deal then they are. They are a tool to remove the need to call `free()` at the right time, with the downside that you don't get to control what the GC thinks is a right time instead.
That's not actually true. They also allow you to do things that you otherwise couldn't. Try implementing persistent [1] maps or sets without a GC.
And my point still stands. The GC allows you to do things you otherwise couldn't.
But if we are talking about the cost of abstractions, the biggest elephant in the room is that Go's GC is NOT optional, which makes it unsuitable for ... (1) systems programming and (2) real-time systems.
C++ and Rust do not suffer from this. And Go is not even suitable for soft real-time systems, because for that you need a GC that never stops the world - right now Go is even less suitable than Java in this regard, because at least for Java you've got the pauseless GC from Azul Systems.
> "But, for systems programming, abstractions suck. They always, always have a cost."
That's a logical fallacy, because if all abstractions suck, then why aren't we doing "systems programming" in assembly (were systems programming is whatever the definition du-jour you prefer to fit Go in)? Clearly, it depends on the project on where it can draw the line, since we are always doing compromises for gained productivity, no? And going back to the non-optional garbage collection that's not even suitable for soft real-time systems, it kind of makes the point on Go avoiding higher-level abstractions on purpose kind of bullshit.
> "It does not make it possible to make things pretty (ugh, nil)."
It's not about pretty-ness, it's about correctness - which in a language containing memory unsafe constructs that can lead to billion dollar bugs (i.e. Heartbleed), is a freaking huge deal. Rust is very innovative in this regard, because it's a systems programming language that solves many issues by means of its more advanced type system - and surely no type system is perfect, but even a single bug that's caught by the compiler, that's a bug that won't reach production.
> "It just makes it impossible (ok, really hard) to overcomplicate things."
I wish developers would stop equating "complicated" to things "I don't understand". That's not what complicated means. Here's the definition: "consisting of many interconnecting parts or elements". That Go doesn't allow certain higher-level abstractions, that's in itself a recipe for complications.
> "for tools that only need to do one thing and do it extremely well, it's either that or C. And I'm not going back to managing my own memory anytime soon"
The choice between C and Go, given that Go is garbage collected, is a false dichotomy.
The argument is a bit more about evolved than that, but flawed nonetheless. The argument usually invoked for Go is that, by eschewing selected language features, it prevents developers shooting themselves in the foot with unneeded complexity introduced by faulty abstractions.
I get the argument. I have seen my fair share of dug-out-from-hell complex projects. What the argument misses though is that not all abstractions are faulty. Computer science, as most science, is a game of ever increasingly abstract reasoning. If implemented correctly, the more abstract the better. The endgame is "Computer, build me a Mars round-trip ship".
Abstractions are good, when well written. They allow us to think on a higher level. Think of them as a fixed learning cost replacing a variable development cost.
Go kind of throws out the baby with the bathwater.
> The endgame is "Computer, build me a Mars round-trip ship".
I think nobody would argue against that endgame, in the broad strokes. But I think Go can be understood as a response to [what the Go developers perceive as] overly expressive languages, languages that have overstepped our ability to responsibly abstract details, languages whose abstractions hide details that are still important and necessary to make explicit.Go is "lower level" in that it purposefully eschews those abstractions, but I think it does that successfully, without a significant loss in expressivity, and with a more-than-commensurate gain in understandability, maintainability, performance, etc.
Take operator overloading. It can be used to create hellish code. It can also be used to create great libraries (numpy for instance). Because of the danger of hellish code, Go makes it impossible to create numpy in Go.
In the end, while Go is simpler, a numpy in Go would be more complex[1], because the language is not expressive enough. The simplicity argument, while true for the language proper, is false for advanced usage.
[1] For example, you can't write Ma * Mb, but must remember the dot product method name.
Rich Hickey's presentation on this topic should be required viewing for everyone: http://www.infoq.com/presentations/Simple-Made-Easy
This is an inadequate analysis. I am writing a soft real-time system in Go, and GC pause simply isn't an issue for me. Go allows one to greatly limit the reliance on GC. The GC in Go certainly places an ultimate limit to the memory footprint of any one Go process, but a whole lot of productive work can be done within such limits.
Also, my program is a rewrite of one in Clojure, so it ran on the JVM. Go is giving me better performance for my particular application. Also given that Go is just starting out in its development, I expect there to be some improvement in the future.
C and Go are just two particular piles of abstractions. The tools work better for some problems, but that's not because "abstractions suck" for those problems.
These languages have built-in abstraction tools (templates) that you can use to create your own abstractions. What I like about Go is the abstraction tools are primitive and allow for consistent & precise expression. The expression may not be as concise in certain cases, however, you can build in the mechanisms into your architecture.
> But, for systems programming, abstractions suck. They always, always have a cost. When abstractions break, you not only have to deal with a broken system but the broken abstraction itself too. (Anyone who has ever seen a gcc compiler error for C++ knows how this feels.)
That is why custom abstractions to your problem domain are important. A framework or a language with lots of features will get you started quickly by providing out-of-the-box tools that you can hang your program architecture on. However, I prefer to have a custom architecture & idioms which are appropriate to the current domain & evolution of the domain.
Well, not really consistent.
For example, try having a range loop for your own structures. Or something like make for them.
And not really precise. The need for interface{} and type switches in idiomatic Go code throws preciseness out of the window.
Despite all these clarity claims, go has significant pitfalls, like the nil channel above (and you will enounter nil channels). There's other things, like "what is a pointer in Go", if your answer involves "*", I urge you to reconsider (hint : what's the difference between []int and [5]int ? Is one of them a pointer ? What about channels (of course I talked about nil channels) ? Maps ?
But every type can be typedeffed to a pointer type of itself, like in Pascal (lots of things look like pascal), and result in completely unpredictable reference or value semantics (or my favorite : partial reference semantics).
Does go have generics ? YES (make, range, ...). Go has something no other language has : return type generic function types (meaning a functions meaning changes depending on what you assign the result to, like range). Does Go have operator overloading ? Is Go object oriented ? YES (including single inheritance). YES. Does go have (complicated language feature X) ? Probably yes. But all of these features are only accessible to Rob Pike, who has apparently decided that nobody has any use for any kind of tree or graph data structures, matrices, complex numbers, or so.
In practice you can catch the go team themselves in errors on the language semantics in their presentations, so I think a VERY strong case can be made that it's not at all that obvious.
But the truth is : this language, due to politics (high position of it's inventor) has 10 or so FTE behind it, with lots of paid people contributing various small bits. Is it anything more than some guys idea of his own favorite programming language ?
The honest answer is simply : no.
The only real advantage Go has is a small, yet functional and pretty complete standard library (like C++ had in the 1980s). It is an advantage that will fade, just like it's faded for every other language.
Built-in slice and map types cover most real-world needs quite neatly anyway.
They also tell me "now you don't have to wait for the language designers or compiler writers in order to 'implement another feature'." Not that _I_ would necessarily be this "brilliant" guy that implements these features. Most likely I will just find some third party library that does it.
This is the "The Curse of C++" and some languages pointed in the article while beautiful and correct at first sight are going down in the same road..
Do we use a programming language to look smart, to create correct code or to efficiently solve problems in a maintanable and sane way?
Go is pragmatic.. theres nothing wrong with that.. but i agree that adding some features to it would not hurt either (like generics and enums) :)
Erlang, for instance, isn't about concurrency. It's about reliability.
Go, I think, is also not about concurrency. It's about building a language that can be sanely used by reasonably large groups of people of varying levels of skill, yet still produce fairly good software even so, without the language forcing a complexity explosion to deal with it.
Consequently, this does not appeal to a lot of relatively skilled programmers used to programming alone. It isn't my personal pick of favorite language, for instance. However, if I could push a button for free, I would convert my workplace of a couple hundred developers to it in a heartbeat, whereas I probably wouldn't actually do that with my favorite language. It is not, of course, a magical fountain of code quality, but it would give me the best tools and best foundation to clean up code bases that in all the other candidate languages I know are one or another sort of mess.
If I were starting a new startup right now and Go were even remotely appropriate, I'd use it. But in my hobby projects? Not really. Except maybe to smash out a microwebsite, it's pretty good there.
So, you know, a lot of the question is what exactly are you looking for in a language? I like Haskell, but the idea of even proposing to change a project at work to it is laughable... and this is important... nor would I expect to enjoy the result two years later if I won. The mess of code that would result from people hitting Haskell with a stick until it did what they wanted it to do would be an unstoppable torrent of ill-conceived code. On the other hand, Go would almost certainly produce much cleaner code, because that's where it really shines. Maybe it isn't "good", but it's the best choice right now in a lot of places.
(It's interesting to contrast Go's approach to this problem with the other major language to tackle this problem space, Java. Despite attacking the same problem, the approaches are significantly different, and I think Go's way better. I'd hesitate to actively predict this, but Java could definitely be feeling some heat from Go in three to six years in a way that very few languages have actually managed to provide any challenge to Java in a long time.)
HN crowd are top smart.. things like Rust and Haskell are a breeze for people here.. but this is not the reality of the tech field.. the majority of people i know in tech, cant handle more powerful languages.. its too much for them
In the end is just that.. know how to choose the right tool for the job.. and dont do it with your ego..
Adaptation is really important.. and in your thoughts we can see a lot of that..
In Wonderland people may have the IQ to spend for the extra concepts and power a language may provide.. but experience is antagonic to this dream..
The cool thing of smart people to make complex things more simple, is that much more people are able to follow.. is the democratization of computing.. this is in total odds against the elitism we can see in some tech circles.. and im totally against it..
I've seen newbie programmers learn Haskell as a first language in under a term. So I don't believe the marketing from the Google people that their language is worse because it is simpler.
Choosing something because marketing told you it was easier is just as silly as choosing something because of ego. Calling people egoists when they choose a tool because of reasoned arguments based on evidence is simply anti-intellectual, and rude.
The problem of 'summing any kind of list' is not a problem that is solved in Go via the proposed kind of parametric polymorphism. Instead, one might define a type, `type Adder Interface{Add(Adder)Adder}`, and then a function to add anything you want is fairly trivial, `func Sum(a ...Adder) Adder`, put anything you want in it, then assert the type of what comes out.
When it comes to iteration, there is the generator pattern, in which a channel is returned, and then the thread 'drinks' the channel until it is dry, for example `func (m myType) Walk() chan->myType` can be iterated over via `range v := mt.Walk(){ [...] }`. Non-channel based patterns also exist, tokenisers usually have a Next() which can be used to step into the next token, etc.
The Nil pointer is not unsafe as far as I know, from the FAQ: http://golang.org/doc/faq#no_pointer_arithmetic
The writer seems to believe that functions on nil pointers crash the program, this is not the case. It's a common pattern in lazy construction to check if the receiving pointer is nil before continuing.
Go is not flawless by any means, but it warrants a specific style of simplistic but powerful programming that I personally enjoy.
And what happens when you don't check? It crashes. That's the unsafe part.
These crashes are simply not possible in Rust and Haskell, and the type system notifies you if failure is possible (because the function will return an Option/Maybe).
You can easily generate a segfault in Rust in 'unsafe' (or 'trusted') code; that might only restrict errors of that nature to code that uses unsafe blocks.
Practically speaking that's pretty common; once you enter an FFI unsafe block, you lose all type safety; but you can totally do it without FFI too. Eg. using transmute().
In fact, there's no way to know if you code contains 'hidden' unsafe blocks wrapped in a safe api in some 3rd party library that might cause a mysterious segfault later on.
You can argue that 'if you break the type system you can do anything, obviously'; that's totally true.
I'm just pointing out the statement: "These crashes are simply not possible in Rust and Haskell" <-- Is categorically false.
You can chop your own arms off in Rust just like anything else (including Go).
Not directly addressing what you're saying, but, IME people are far too quick to use `unsafe` code. One needs to be quite careful about it as there's a pile of invariants that need to be upheld: http://doc.rust-lang.org/master/rust.html#behavior-considere...
> once you enter an FFI unsafe block, you lose all type safety
You don't lose all type safety, especially not if the FFI bindings you're using are written idiomatically (using the mut/const raw pointers correctly; wrapper structs for each C type, rather than just using *c_void, etc).
I disagree: if the construction can fail, the constructor must return an error, which will be checked; only if the error is nil can the process continue. There shouldn't be logic on the actual data returned to assert whether a constructor worked or not.
http://play.golang.org/p/eqnDLVMHGA (pseudocode)
If that's so, it's because it's a language that also fights lots of things a modern programmers wants to do/have.
Actually using channels as a general iterator just for the sake of using the range operator is considered as an anti-pattern. The reason is not performance (although it has a cost), but the risk of leaking producer goroutines. Your example:
for v := range mt.Walk() {
if blah {
break
}
}
How will the goroutine writing into the channel returned by mt.Walk know when there are no more consumers which will possibly read from it?One way out is:
done := make(chan struct{})
for v := range mt.Walk(done) {
if blah {
break
}
}
close(done) // or defer close(done)
Picking the right cleanup is error-prone.What about errors? How will mt.Walk tell you that it had to interrupt the iteration because an error happened? Either your channel has a struct field containing your error and your actual value (unfortunately Go lacks tuples or multivalue channels).
Furthermore uncaught panics in the producer goroutine will generate a deadlock, which will be caught by the runtime, but it will halt your process. One way to do it is:
errChan := make(chan error)
for v := range mt.Walk(errChan) {
if blah {
break
}
}
err := <-errChan
The producer will use the select statement to write both to errChan and your result channel. The success of writing to errChan is a signal for the producer that the consumer exited.
However same thing here about relying on the last statement being executed to avoid a leak in case of returns or panics. Here the defer is less nice since you're supposed to do something with the error: func Example() (err error) {
errChan := make(chan error)
for v := range mt.Walk(errChan) {
if blah {
break
}
}
defer func() {
err = <-errChan
}()
}
Next-style methods just pass through the panics, and allow you to handle errors either by having a func Next() (error, value) or with this pattern which moves the pesky error handling outside: i := NewIterator()
for i.Next() {
item := i.Item()
...
}
err := i.Error()
First, any panic that happens inside either your code or the generator will bubble through.
Second, if you return from your loop body, you will have to provide your own error (the compiler will remind you about your function signature, if in doubt). You can return early if the iterator can be stopped and GCed out (i.e. it doesn't handle goroutines or external resources), otherwise you'd have to call a cleanup as with channels.The rule of thumb with Go should be that you don't have to do things just because they use some syntactic sugar. After a while you start to think about beauty in terms of properties not about calligraphy.
However, I do see this as a weak point of the language, which hopefully can be solved by education; after all Go is so simple to learn that you might be tempted to make it look even simpler. But the fact that the language has (almost) no magic, it means that you can actually understand what some code does, which imho outweighs the occasional syntactical heaviness or having to learn a few patterns.
... which is exactly what the article mentions and criticizes?
// Do NOT reorder this, otherwise parallel lookup could find key but see empty value
atomic.StoreInt32((*int32)(unsafe.Pointer(uintptr(uint64(slot)+4))), val)
atomic.StoreInt32((*int32)(unsafe.Pointer(slot)), key)
However, the non volatile, non unsafe parts of the code were an absolute joy. Testing was a joy, compiling was a joy, and benchmarking was a joy. I was impressed that it allowed me to bypass the type system completely and do nasty, nasty things in the pursuit of performance. I want a language that lets me do nasty things where I must, but that makes the other 95% of the program, and the job of compiling, testing, and maintaining that program easy. Go excels here. Rust, C++, Haskell, Scala will never be good at that because they're too damn complicated (although each of them make the nasty parts a little less painful!)The end result of my weekend's hacking? On an i7-4770K @ 3.5ghz
BenchmarkGoMapInsert-4 20000000 110 ns/op
BenchmarkHashIndexInsert-4 100000000 25.6 ns/op
BenchmarkGoMapLookup-4 50000000 78.5 ns/op
BenchmarkHashIndexLookup-4 100000000 17.7 ns/op
About 4x faster than Go's builtin map, for int32 key/value on both insert and lookup. And it allows any number of reader threads concurrent access with a writer without any synchronization or blocking, unlike Go maps. It doesn't allow zero keys, unlike go maps, and it doesn't allow deletes. Hardly apples to apples, but the performance of pure Go code is impressive nonetheless. 200 LOC, not counting tests.FWIW, I actually think that Rust positively excels at this sort of isolated low-level work due to explicit `unsafe` blocks. Furthermore, the type system is more expressive meaning the need for this is rarer[1].
In my experience, the rest of the language (i.e. non-`unsafe` things) works very well for maintenance and testing, also in part due to the more expressive typesystem, and things like algebraic data types with exhaustive matches by default (I've done some huge bug-free refactorings to the standard library and compiler, mostly due to the compiler automatically catching all the places that need updating).
On the other hand this comes with the cost of making the "job of compiling" more difficult: the compiler complains about more things.
Re testing: there's unit testing and microbenchmarking built-in: http://doc.rust-lang.org/master/guide-testing.html
[1]: in this case, the type system positively designed with making this sort of concurrency safer.
Rust actually isn't that complicated. Don't get discouraged by comparisons to Haskell — it's still a C-family language where you can play with pointers and mutable state.
To me Rust still feels like a "small" language (similar size as Go or ObjC, not even scratching complexity of C++). It's mostly just functions + structs + enums, but they're more flexible and can be combined to be more powerful than in C.
I'm much more familiar with Haskell than Rust, but having played around with Rust I think they're on a par with each other in terms of difficulty, depending on your background.
Deleted comment
Perhaps I wasn't clear in the post you're responding to: my point was that both Rust and Haskell are fairly "simple" programming languages which seem more complicated, because they introduce a lot of features which are likely to be new to those who are using it for the first time. I wasn't really comparing them as languages per se; that's a separate discussion.
> Common in any language, including Go.
Higher-order functions are common in most languages, but not in the way that Haskell does. Most languages use first-class functions as lists of instructions (do some stuff, and perform the steps in this argument). Haskell makes them truly first-class, such that they're positively ubiquitous: an example is currying, which is everywhere in Haskell and rare in most other languages; another example is monads, which are obviously a core part of Haskell and which require first-class functions (e.g. in >>=) to do anything useful. There are other examples.
> Rust does not have these.
I know; I was speaking about Haskell.
> This is because we want memory safety without performance tradeoffs (global concurrent garbage collection).
Right; it's a perfectly understandable thing to have, but it's not something that (to my knowledge) exists in any other mainstream language. It's an example of something in Rust which is obscure to newcomers.
> Could you elaborate?
I'd have to write some code and run the compiler to get the actual error message, but I recall getting errors about using some reference outside of a context or something. In my fuzzy recollection, it would be something like where I had written `match foo { a => b; c => d}` and I would get some error message which would be fixed by writing `let foo1 = foo; match foo1 {a => b; c => d}`. Unfortunately I don't remember the specifics, but long story short: compiling Rust code produces a lot of very strange error messages to someone unfamiliar with the language. :) In this way it's not dissimilar from Haskell.
> This is because dynamically-sized types are not yet implemented, but they will be for 1.0.
Great to know! If only there were a more helpful error message than "Bare str is not a type." :)
Why is Rust too complicated to allow you to do low-level hacking?
It's 2014 already. Angle brackets, arrows, and pattern matching are 1990 level language technology.
Heck, even a dynamic front-end language like Coffescript has these kind of things nowadays.
This week is week two of my being contracted by Mozilla to write docs full time. First up, a new tutorial. You can see my work from last week http://doc.rust-lang.org/guide.html , and my first task after I finish breakfast is to clean up https://github.com/rust-lang/rust/pull/15229 , which got some review over the weekend.
So, you're right (at least about the docs) but I'm on it.
I ask because this has not been my experience writing several hundreds of thousands of lines of Rust code, nor has this been the experience of anyone I have helped get up to speed. Moreover, I believe there is no feature in Rust that is not necessary to achieve safety without sacrificing performance.
...
And can I get in on some of that? ;-)
You mean readers concurrent with a writer? AFAIK, any number of reader threads can get values out of a Go map when it isn't being written to.
Need it for floats, duplicate it again.
This is a solved problem -- the fact Go doesn't have the solution reflects very poorly on Go.
Perhaps our ultimate quest in terms of designing languages is to design one smart enough that can be used to program toasters and clusters alike. Until then, we might as well use the right tool for the job.
I think the issue Go detractors have is that it is none of those things, nor is there any pair of those things for which there is no better alternative than Go. If you want fast and memory efficient, you could pick C++ or C. If you want something a little easier to program in, you could pick C#, which dominates Go in all three categories. If you want to go easier to program in, there are plenty of languages like Python that are more powerful than Go.
From my initial dabblings with the language, it feels like its constraints may not actually be a big deal in practice, and may even be more of a help than a hindrance in large projects. It would be nice to get some commentary from more experienced go users.
Initially I felt the same as you: Go was much easier to get things done in, and I could be reasonably productive quite quickly (moreso than Haskell, which I found very difficult to learn).
However, after some time I found many of the same problems mentioned in this article. Particularly, in many cases I had to fall back to the kind of nasty unsafe code mentioned in this article (like using interface{}). Often, I felt that my code was needlessly verbose. I would frequently write code and feel that the language was preventing me from doing what I wanted directly. Ironically, this is exactly how I felt with Haskell at first (not anymore).
Ultimately, I ended up switching to Haskell, and although it was significantly harder to learn, I felt like it has a lot more flexibility, safety, and importantly lends a clarity to thinking when designing a program.
The author's conclusion:
· Go doesn't really do anything new.
· Go isn't well-designed from the ground up.
· Go is a regression from other modern programming languages.
is hardly sustainable. Go was production-ready in 2011 with a stable version 1.0. It has a surprisingly mature tool chain and vibrant community. Go cross-compiles from my 64-bit Mac to a 32-bit Raspberry Pi or ARM Android phone on a whim. I can deploy my app by copying a single, self-contained binary. Tell me again that Go does nothing new for us.Go makes concurrent programming safe and easy (with a nice syntax) -- something that we frankly should have done 30-40 years ago when we first started thinking about multiprocessing. Go was invented by folks like Ken Thompson (who created Unix) and Rob Pike (who created the Plan 9 operating system and co-created UTF-8). Tell me again that there isn't good engineering behind Go.
Finally, Go attacks the needs of modern programming from a different paradigm than we have been using for the last 10-20 years. From the first paragraph of Effective Go:
> ... thinking about the problem from a Go perspective could produce a successful but quite different program. In other words, to write Go well, it's important to understand its properties and idioms.
So of course it's different than a lot of other aged languages. Go tackles newer problems in a newer way. Tell me again that Go is a regression from other programming languages.
None of the things you mentioned are new.
> Go makes concurrent programming safe and easy
Mutability & concurrency, nils, interface casts -- these things all go against safe.
> Tell me again that there isn't good engineering behind Go.
You seem to think that a language that has baked in syntax for concurrency, or that has famous people behind it necessarily has "good engineering" behind it. I don't understand how one leads to the other.
When so many mistakes and regressions go into a language, one shouldn't care that famous names are behind it.
> Go tackles newer problems in a newer way
Go is essentially Algol 69 with baked in concurrency syntax.
> Tell me again that Go is a regression from other programming languages
Losing null safety, sum types & pattern matching, parameteric polymorphism and type-classes, all form a huge regression in PL design from the state of the art.
You're thinking in terms of "here's this set of bullet point features that I think a language has to have to be a proper, modern language." But the grandparent was asking you to consider that a different set of features might have value form some real-world problems that Go's authors had really bumped into. You reply, "Nope, couldn't have - it doesn't have my bullet point features!"
There are more things in programming than are dreamt of in your philosophy of what a programming language should be.
He said Go makes concurrency safe & easy, when Go emphasizes features that contradict safety and ease.
He said Go tackled problems in a newer way, when Go is really Algol69 + coroutines.
He denied Go regressing from other languages, when it throws away decades of PL research.
In none of this did he say "Here's an alternate set of features that ...". No. He said concrete, specific, wrong things.
What you are saying is a different thing -- and I also disagree with you.
These "bullet list" features weren't invented for the lols. They were created to solve real problems. Problems that Go doesn't have an alternate solution to.
Go programs dereference null. That is a bad thing. Languages with my "bullet point features" do not dereference null.
Go programs duplicate code to handle different types. Ditto.
Go programs can (and thus do!) mutate some data after it was sent to a concurrent goroutine. Ditto.
Go programs can cast down to incorrect types. Ditto.
The "bullet point features" are important. There are alternatives, but Go doesn't sport any of them.
I do agree with the author here: Go the language does nothing new. Go the platform, on the other hand, is a really pleasant new experience when compared with other languages.
The language is a regression in features compared to what other languages can do, but that is totally understandable when you look at what Go is aimed at.
I love Go, because it fits in my head.
This. I love Go's simplicity. Coming back to Go code I wrote months ago, I can immediately understand what it does virtually every time, which required lots of discipline I didn't always have in other languages. Lots of languages have obscure corners that allow you to do really cool things that aren't obvious, but for the most part, Go doesn't have these; what you see is what's happening.
Are there things that would make Go a better language? Sure! Should the type system be improved? Yup! One thing that makes me cringe is when I open up library code and see interface{} and calls to the reflection package all over the place, but general solutions often require that in Go, and that's a problem. In practice, though, this is almost a feature: if you see that stuff in code you're reading, it's a giant red flag that this code is tricky and possibly slow, and care is needed.
Edit: speeling
I don't think golang invented static linking. ;)
Go does, however, have a very pragmatic feel to it. The creators, in general, seem to take a very measured look at things before adding them, and are very careful to keep the compatibility promise for 1.x. The overall result feels very "engineered" (especially when using the tooling).
Go clearly isn't perfect, but yet it feels rather robust for such a young language.
And while the Hindley Milner type system is a wonder to behold and I love working in languages that have them sometimes those same languages introduce a non-trivial amount of friction to development.
Go's single best feature and the one around which almost every decision in the languages is centered is an almost total lack of developer friction. If Go has a slogan that slogan is "Frictionless Development". It's easily the simplest, least annoying, and most "get out of your way" language I've ever used.
[EDIT: some wording was incorrect]
I suspect this is where many philosophical differences in these discussions originate. I appreciate the value of having quick and easy tools, but for production software where I care about quality, I don't want the language to get out of my way if I'm doing something silly, like treating data as if it's a different type to what it really is or assuming there is data to work with at all if a null value is a possibility. The web is plagued by security problems, so it seems odd to me that anyone would promote a new language for writing web-based software that retains obvious and entirely avoidable ways to introduce vulnerabilities.
Unless you want to do generics. Of extend the language to have custom operators, for things like scientific computing. Or tons of other things.
But, you know, bad for a teaching language.
Author here. Depends on what I'm doing. For most simple programs, the things I listed in the article don't really get in the way. So writing my web server in Go was not that bad at all. It was pretty good, in fact.
It's when I start making larger programs that I start feeling the constraints of the things I listed in the article. Having a strong, capable type system really helps me keep track of large projects.
Compared to other popular programming languages aimed at web programming, such as Python, Ruby and PHP, Go provides more type safety. Comparable to Java's but for less code.
Go's runtime and development tools are very lightweight, which is important to me as I use multiple, often dated computers with limited memory.
It is very easy to learn, a low investment. This means that it is conceivable for a student previously only exposed to Java to get on board on your software project on short-time notice.
Just a note: I don't think it is fair to say Go has absolutely no immutability as it was defined, it does have "const". See http://golang.org/ref/spec#Constant_expressions
I absolutely agree that Go is nice for writing web servers! However, there is no reason that it can't still be nice for that and also a well-designed language in general.
For example, Haskell has awesome concurrency features, and writing a web server in Haskell is reasonably nice (not quite as nice as in Go, IMO).
Edit: While `const PI = 3.1415…` is threadsafe, it's not very useful in comparison to runtime-immutability :)
Also I just noticed with Go's Unicode support we can write `const π = 3.14..` if we really wanted.
As just one example, ADTs in Haskell are implemented in an extremely efficient fashion.
Type classes are implemented in the same way that Go's interfaces are implemented (basically the same way as vtables are in C++).
The immutability features (const) are compile-time checks, and can even help the compiler be more efficient.
"if as an expression" has no real cost.
Actually, it's because I like Go's standard library HTTP server implementation!
I'm not claiming that Haskell or Rust are magic bullets, or that Go is useless. Far from it!
The claim that it is "no longer a practical language" is as silly as the "Real World" fallacy.
> A Good Solution: Operators are Functions
> A Good Solution: Algebraic Types and Type-safe Failure
> A Good Solution: Pattern Matching and Compound Expressions
People have tried this approach. See languages like C++ and Scala, with hundreds of features and language specification that run into the thousands of pages.
For an unintentional parody of this way of thinking, see Martin Odersky's "Scala levels": http://www.scala-lang.org/old/node/8610
For additional hilarity, note that it is an undecidable problem whether a given C++ program will compile or not. http://stackoverflow.com/questions/189172/c-templates-turing...
--
Go was created by the forefathers of C and Unix. They left out all of those features on purpose. Not unlike the original C or the original Unix, Go is "as simple as possible, but no simpler".
Go's feature set is not merely a subset of other langages. It also has canonical solutions to important practical problems that most other languages leave do not solve out of the box:
* Testing
* Documentation
* Sharing code and specifying dependencies
* Formatting
* Cross compiling
Go's feature set is small but carefully chosen. I've found it to be productive and a joy to work with.
>Go was created by the forefathers of C and Unix.
Yeah, and it's obvious (and sad) they ignored the last twenty years of PL research and progress.
>They left out all of those features on purpose
Did they? I don't believe this is the case, as I've heard from the creators many times that they want to add generics but haven't figured out the details yet.
Are you really going to sit here and argue that static typing is important EXCEPT for when working with collection? That parametric polymorphism doesn't make things simpler?
More than thirty years (at the time it was released), the first language with "modern" generics was ML in 1973.
Of the 4 you mentioned (Constraint based generics and parametric polymorphism, operators as functions, algebraic types and type-safe failures, and pattern matching/compound expression) C++ really only has 1 (operators as functions).
>with hundreds of features and language specification that run into the thousands of pages.
This describes neither Rust nor Haskell.
>Go is "as simple as possible, but no simpler".
It has mandatory heap usage, garbage collection, green threads. It's more than generous to call that "as simple as possible".
Of the 5 features you mention that Go has "canonical solutions" to (in the form of external tools), I know off the top of my head that Haskell's Cabal takes care of at least 4 of them. I'm not sure about formatting. Rust probably has similar tools, or if it doesn't, they can certainly be added without changing the language.
* Testing
Built-in: http://doc.rust-lang.org/master/guide-testing.html
* Documentation
Built-in: http://doc.rust-lang.org/master/rustdoc.html
* Sharing code and specifying dependencies
The newly released 'cargo': http://crates.io/ https://github.com/rust-lang/cargo/ (alpha, but quickly improving). This will be Rust's cabal equivalent, almost certainly with support for generating documentation and cross-compiling (it already has basic support for running the tests described above).
* Formatting
Missing at the moment, but very wanted: https://github.com/rust-lang/rust/issues/3195 .
(Well, to be precise, the compiler has the '--pretty normal' option, but it's not so good. https://github.com/pcwalton/rustfmt is the work-in-progress replacement.)
* Cross compiling
Already supported, although it requires manually compiling Rust with the appropriate --target flag passed to ./configure, to cross-compile the standard library.
> I know off the top of my head that Haskell's Cabal takes care of at least 4 of them
from the post I was replying to.
It is possible to do type parameters in a way that is simple yet effective. But I can understand why it wasn't done this early in Go's lifetime, especially since Rob Pike isn't exactly well into generics (vs. Odersky's experience with Java/Pizza).
The null pointer was created by Tony Hoare. He later thought that that was a mistake.
Yet here we are again, in the new millenium. Coming up with new languages with null/nil pointers in them.
Here's my reasoning. I'm a fan of human language & domain ontologies. Word definitions are quite flexible & do not have an elaborate type system. I don't feel the need to have a provably correct logical system to have a useful conceptual tool (i.e. analogies). I enjoy ambiguity. Ambiguity can lead to paradoxes, which in turn leads to exploration & novelty.
Strongly typed systems, by default, give me the impression that the domain ontology is figured out on a highly precise level. That is never the case. You can almost always go deeper. Domain language precision is tough to model & express.
I prefer data structures to drive operations. I suppose that a schema is often useful, however I don't feel like I need the programming language to enforce the schema.
I also like to evolve the design, using tests. Tests are really examples to exercise the program's API with expected I/O.
People often equate an evolved programming language/paradigm as being better. In the case of Javascript, they point out that is was created in a few days as evidence that it's "bad". The thing about an evolved language/paradigm is it has evolved down a certain path. That often means restricting the freedom of the programmer to evolve the program down another path. I'm not picking one way to be better than another. However, I do see tradoffs to both approaches. I personally prefer a more flexible language. It can be evolved, as long as the evolution does not restrict my freedom to evolve the program.
It explains how natural language is a very poor way to express programs, and how it held back science and progress for many centuries.
Strong types describe your code precisely. If your code doesn't match the model yet, that's fine.
But your code has invariants in it. Things like: "this variable can never be nil, that variable can". These invariants can relatively easily be encoded as static types. Not doing so is just throwing away safety and documentation for virtually no benefit.
Other invariants are similar. Instead of documenting them or keeping them in your head, you let your compiler worry about them. And then when you break those invariants, the compiler is your friend! He helps you go and find all the other pieces of code that relied on the broken invariant, so you can fix them.
You say you prefer a more flexible language: But Go is extremely inflexible. It has a very primitive set of tools to do everything, clumsily. A language like Haskell, for example, lets you have Go-like coroutines and channels. But it also lets you program with software transactional memory, or use other parallelism constructs.
Also, the inability to specify invariants of your program isn't flexibility. The ability to specify them or opt out of specifying them, which is what strong type systems give you, is.
1. https://www.cs.utexas.edu/users/EWD/transcriptions/EWD06xx/E...
I'm not interested in using natural language to implement the software (write code). I'm interested in using natural/technical language to create an ontology for the architecture. This is where things get gray.
When I think of an architecture, I think of something that evolves over time. I think of architecture as a tool to facilitate communication between programmers, designers, project management, domain experts, & users.
This ontology evolves over time as the software, understanding of the domain, & the domain itself changes.
I see this fuzziness as an accurate model of the conceptual domain, which is ultimately based on the understanding of multiple humans. This understand is fuzzy and heavily dependent on context. And yet, the ontology attempts to coral this fuzziness into more strongly defined concepts, which map to the implementation. The implementation should not be fuzzy at all.
> Other invariants are similar. Instead of documenting them or keeping them in your head, you let your compiler worry about them.
I usually use guard clauses to protect against nulls. I rely on my tests & production monitoring systems to prove that the implementation is incorrect. When there is such proof, I correct the system. In environments that support rapid feedback & deployment, like the web, this works well. In environments that don't support rapid deployment, iteration, and where lives are at stake, not so well.
> But Go is extremely inflexible. It has a very primitive set of tools to do everything, clumsily. A language like Haskell, for example, lets you have Go-like coroutines and channels. But it also lets you program with software transactional memory, or use other parallelism constructs.
That sounds good to me.
> Also, the inability to specify invariants of your program isn't flexibility.
That mostly sounds good. I would want invariants to be optional, which sounds like is the case.
An interesting (to me) insight was that in a language with a flexible type system, the types are effectively just a set of assertions at the start and return of every function, that say that the inputs and outputs have certain properties. With a compact syntax and zero runtime overhead, which is nice.
I do think that some strongly typed languages make it too difficult to step outside the type system; in Scala I have to do something like (x.asInstanceOf[{def foo(): String}]).foo() whereas in Python I can just write x.foo(). But once I started seeing the type system not as a fixed piece of the language but as a framework for encoding my own assertions, it became useful enough that I can't stand to live without it.
Note the Scala verbosity here is Scala-specific. In HM-style languages, type inference works much better and you don't have to do such things. You might still have to explicitly "lift" a value from one type to another (e.g: Wrap a value in "Just", or use "lift"), but that's a much more minor price to pay.
So what does this have to do with Go or type systems?
> I usually use guard clauses to protect against nulls. I rely on my tests & production monitoring systems to prove that the implementation is incorrect.
And that's a bad thing. There are better tools for this job. What's the downside of encoding nullability into the types?
> That mostly sounds good. I would want invariants to be optional, which sounds like is the case.
Every good type system lets you "opt out".
Therefore, it is a bit silly to look at dynamic typing, where you cannot "opt in", as more flexible.
I've found that type systems, that aren't utilizing Duck Typing, as being restrictive & causing incidental complexity when evolving the design. I don't really care if something is a categorization of something else. I usually (> 98% of the time) only care if that something adheres to an interface.
I don't like to label people in life either :-)
> I usually use guard clauses to protect against nulls. I rely on my tests & production monitoring systems to prove that the implementation is incorrect. >And that's a bad thing. There are better tools for this job. What's the downside of encoding nullability into the types?
For the web, it's not that bad. The design is constantly evolving, so most of the development period is spent completing something that is not finished.
There's no downside in encoding nullability, unless extra syntax & incidental complexity is added. It's not a big problem for me so I'd rather not have to do extra work for this feature.
> That mostly sounds good. I would want invariants to be optional, which sounds like is the case. > Every good type system lets you "opt out".
Explicitly or implicitly? I'd rather be opted out by default and opt in when I want to. Again, I don't want to do extra work or have incidental complexity.
More complex type inference requires a more complex (and hence buggier) compiler.
Finally, the author should investigate the unsafe package; I believe the following code will do what he wants:
*(*byte)(unsafe.Pointer(uintptr(0x1234))) = 0xFF
Verbose? Sure.I like most of Go so far, but interface{} is possibly the ugliest artifact of a programming language that I've seen, next to pretty much all of c++
Rust and Go should have a baby
`range` can be used to receive values on a channel, which is certainly not a known size and doesn't have guaranteed termination.
Go is more productive than C++, but less so than Python or some other alternatives. Go's tooling, linking and libraries make it useful in the Cloud, less so on mobile or personal computers. And the lack of third party libraries, combined with a relatively slower speed of developing these libraries (again compared to Python, javascript and others) means that Go will have a hard time going beyond cloud services.
For me it is a language that feels like a hybrid between a scripting language and a 'real' programming language. Simple syntax with some powerful, easy to use features, impressive library support for being only a few years old, but compiles (static) to native code.
That fills a gap that Haskell and Rust don't, These more advanced languages sacrifice simplicity for an attempt to be perfect. Go makes the clear statement of being simple above everything else.
Give an average python/ruby/<insert scripting language here> coder the link to "A 30-minute Introduction to Rust" ( http://doc.rust-lang.org/intro.html ), and he/she will give you a strange look and not understand half of what is being said there. In the end they'll conclude it's not something for them. Give it to a C++ coder and he'll say 'oh nice, but I can do that in C++, use Boost<whatever>, because C++ is superior to all!' - and that coder there is their target audience. A decent C++ coder will have invested too much time to learn another language to solve problems he already learned to solve for himself in C++ a long time ago. Rust might be better and would make his life easier in a lot of cases, but still the majority won't make the switch.
Give the same <insert scripting language here> coder the Go documentation, and he'll be off in no time, writing better code than he used to do, producing a single binary which will not be an absolute nightmare to deploy. And that's what every coder of scripting languages has always dreamed of - being able to make programs in a simple straight-forward way, with as little dependencies as possible, without needing a <language X> runtime. On top of that, Go makes cross-compilation dead-easy.
There are a LOT more <insert scripting language here> coders out-there than there are C++ programmers. Giving them Go makes running the stuff they write more efficient confronts them with Git/source control (you would be surprised how many don't know about SCM)
Maybe its because of the creators, Google backing it, or the promise that 1.x remains compatible, or that it ships with a standard library good enough to write useful server stuff.
So despite all those flaws (I miss generics the most), I think it will become the static Python replacement for the next 10 years.
(Its like how Factor handled 3rd party contributions: one library for some particular task is blessed and shipped w/ Factor. Of course it doesn't scale..)
Go aims to be more simple and concise, in the end you write less code to do the same thing, as you would in C++, Haskell or Rust.. because those 3 languages decided to "cover everything" and are worried about other things, creating more burden to the programmer, but with something else to gain
Go is more of a productivity language.. it remind us the we have better things to do in life, and not spend all the time coding, but enjoying that extra time with your family for instance..
Therefore Go is good.. its only MAYBE "not good" for the same thing that Rust, or Haskell are..
Besides.. this is the wrong way to market some technology or idea.. the best way would be "Why Rust or Haskell are Good" instead of envy the success of others..
Its all about tradeoffs.. and i think this article misses the point.. and care only some things that will obviouslly make some languages more fit.. like, if you care more about memory control,type systems and safety.. its obvious that Rust and Haskell will look good and "correct"
But this is not all about it.. theres team working, productivity.. its a balance.. and always depends of the problem domains.. some language are more fit than others.. theres no need for bashing
As a data point, here are links to the Haskell and Go implementations of the TechEmpower benchmarks:
Haskell (78 sloc)
https://github.com/TechEmpower/FrameworkBenchmarks/blob/mast...
Go (164 sloc)
https://github.com/TechEmpower/FrameworkBenchmarks/blob/mast...
To see the reality of it.. a better example would be something without any support library...
Cherry picking is easy..
From the same benchmarks Game:
spectral-norm - Go
http://benchmarksgame.alioth.debian.org/u64/program.php?test...
spectral-norm - Haskell
http://benchmarksgame.alioth.debian.org/u64/program.php?test...
I didn't cherry-pick btw, I just went to the first benchmark which included community-written snippets of both Go and Haskell I could think of. Cherry-picking would be me intentionally skipping over examples such as the one you provided and instead posting my example.
You can see from the messages in the code that these 2 programs do completely different things.
I sincerely doubt that Go is more concise than Haskell. I won't say whether concise is good or bad, but I very much doubt that Go is the most concise.
Bound mismatch: The generic method immutableEnumSet(Iterable<E>) of type Sets is not applicable for the arguments (Integer). The inferred type Integer is not a valid substitute for the bounded parameter <E extends Enum<E>>
Sorry for advanced type systems but I really want to go back hacking Go code :)
In this particular case, you're using an Integer where a subclass of Enum is called for. The value you're passing may very well be a valid value for the Enum you're trying to use. You may be doing something silly, or it's possible that this is an artifact of generics being bolted on to Java after the fact. In this case, it may be possible for the compiler to infer which Enum you really wanted and insert a runtime check and cast, but then it would be doing you a disservice by silently inserting an opportunity for a runtime error.
I'm not advocating Java's type system, but be glad Java at least has typesafe enums. Every couple of years (across several employers) I run into a very bad bug due to two different return code enums happening to use either 0 or 1 as their "ok" values, and enums of one type being silently cast to the other, resulting in silently okay behavior in the common case and spectacularly bad error recovery in corner cases. Just today I fixed an error where someone had designed an API where an enum of one type was passed to a function needing an enum of a different type, without any translation. Some users had gotten correct behavior by passing an enum of the incorrect type to the API, and some users had followed the API documentation and gotten wrong behavior.
* the indexing makes a map[something]boolean act like a set. Sets and maps are so similar it always felt wrong for them to be two separate constructs.
* making exported functions/vars/etc begin with a capital letter. When naming important stuff, it's a relief not worrying about naming conflicts with keywords. When naming locals, just use i,j,p,q,p2 anyway.
* using defer and recover instead of catch and finally. The catch clause is really two functionalities rolled into one and using defer and recover decomplects them.
Other languages should copy those.
What I'm concerned about...
* printf and regex notation are used so much they're really part of the language, but have an entirely separate syntax embedded within strings which must be learnt. But unlike the rest of Go's syntax, they're unintuitive, especially regexes for Unicode. Unicode is meant to be one of Go's strengths. I understand quick parsing is one of Go's primary reason's for existing, but the regex and printf notations could have been cleaner. When you think about it, why are the arithmetic and bitwise operators generally part of a language's primary syntax, but string matching and formatting delegated to sub-languages?
* statements, like if/else and ++/--, don't return values in Go which is hard to get used to. I understand making statements generally be shorter so the code looks good after running through gofmt could have motivated this.
Overall, I think Go's a systems language intended for quick parsing and eliminating C++'s complexity, and the author's comparing it to languages with far higher level constructs. The correct solution is for people to implement languages like Haskell and Clojure in Go, making them execute as fast as possible.
Uh, what? Haskell already compiles to native code, and is faster than Go in many cases.
Also, if you were implementing a programming language, there are much better languages to do it in than Go.
Also, if you want to implement a compiler, and not an interpreter, the host language having GC is not very useful to get GC.
Haskell is going to make working with ASTs much easier and safer. It also has a superset of the concurrency features of Go.
You also don't have the ability to write a GC-less language, because there is no practical way to write non-GCed Go code.
>you can incorporate a few nice concurrency features with little effort
You also can't implement any custom OS-level concurrency features.
True, so you probably don't want to do that.
You also can't implement any custom OS-level concurrency features.
True. But for "journeyman" level language implementation, the toolset is quite good.
No, you really don't. The built-in GC is nothing like the GC needed for lots of other languages.
Don't write those languages in Go.
Every language, including all the languages described in this article, goes through a period of instability while it figures out what works and what doesn't.
Author's point was that we should not use "not good" languages for the fear that we might be stuck with them for next 20 years. I'd rather be stuck with a language whose designers are very resistant to change vs one that gets features haphazardly bolted on every few years (PHP comes to mind).
I absolutely agree! However, I don't think Rust will continue to go through wild changes for much longer. My guess is that it will settle and become pretty fixed.
And Haskell certainly doesn't introduce breaking changes very often.
We're shooting for the end of the year, in fact. You can view the list of backwards incompatible language changes here: https://github.com/rust-lang/rust/issues?labels=P-backcompat...
Actually, I'd say instability is one of the significant challenges with adopting Haskell for long-lived production code. For example, there have been a few discussions in various forums and blogs recently about how much of Real World Haskell no longer even compiles on the latest GHC and current versions of libraries. RWH is a book that rapidly became the go-to text for new Haskell developers only a few years ago, so we're not talking about either bleeding edge functionality or a length of time where software written back then has probably been retired here.
So stability is perhaps an area where Go does have an advantage over the likes of Rust and Haskell today. Rust is still evolving as a new language inevitably will; it has not yet reached the level of stability needed for long-term production use by the general programming community. Haskell is also still evolving, but for a different reason: it is valued as much for being a test bed of bleeding edge programming language design as it is for being a practical programming language.
Perhaps Haskell the core language doesn't but ghc certainly does, in every major version.
Every single thing listed in this article could be added to TI BASIC at any point. It would just require a complete re-formulation of the language into something completely unrecognizable.
The <> notation in id<T>(item for generic bracketing is harder to read than other bracketing symbols, e.g. () [] and {}. Unlike those others, angles are used for comparison ops and arrow heads also. If Go ever introduces generics, the Scala-like [] notation looks cleaner and would fit into Go's existing grammar.
type Foo[T] T
versus type Foo []int
for example. type Array[T] []TIMO when evaluating programming languages, we should not only consider writability but also its readability. This is especially true if many engineers are going to be involved in the development.
It is good to have type inference and operator overloading in terms of writability. Nobody wants to type verbose code.
OTOH some verbosity within the source code helps reading the code. And type information (which type inference and operator overloading tries to hide) is one of them.
So I can respect Go's decision not to support operator overloading / only support some part of type inference.
Well, I think it's a good idea to get people thinking about programming language design. Sometimes it's really hard to tell what's wrong with something if you don't know about anything better.
Because if everybody was selfish and self-absorbed enough to do that there wouldn't be any evalutation of languages outside the personal level?
The way things move forward is through (1) criticizing stuff, (2) fixing stuff, (3) making new stuff (in that order). And all three steps are necessary.
If the added complexity is "good" to you, then fine. In modern systems, simplicity is a powerful debugger.
Adding all those features that the author talks about -- "Constraint-based Generics and Parametric Polymorphism", "Algebraic Types and Type-safe Failure Modes", and "Pattern Matching and Compound Expressions" -- even if useful, would defeat the purpose of Go.
To mean anything Go doesn't currently have?
It is more important for the implementation to be simple than the interface.
Doesn't that make programming languages themselves complexity? After all, you can already do anything in assembly.
That seems like a really weak argument. Sometimes having a more "complex" (in your terms) system leads to simplicity. For example, programming languages in general. Programming languages add "complexity" to computers over machine language programming, but the result is that making a program is a much simpler task.
I don't consider the features I mentioned in this article to constitute "complexity".
I think that Haskell is a beautifully simple language, in the same way that e.g. Euler's identity is beautifully simple. The reasoning behind it may be somewhat complicated, but the result is very simple (and impressive) to behold.
Also, as for a "huge amount" of corporate support, if we see the equivalent of "Enterprise Java Beans" then I'll concede that Go is "another Java."
Similar to Java: The barriers to outreach are small because the language is in many ways familiar. I think that's a wise and pragmatic choice.
>If you want to modify a data structure, you have to create an entirely new data structure with the correct changes. This is still pretty fast because Haskell uses lazy evaluation.
I believe the issue is persistent data structures -- the new data structure "remembers" the old one (instead of recreating it) and records changes. (Clojure works like this as well) -- and not lazy evaluation.
If you haven't looked at persistent data structures yet then I'd definitely recommend doing so because they are fascinating. A few people have written about Clojure's data structures and the following article looks like it gives a good introduction:
http://hypirion.com/musings/understanding-persistent-vector-...
NO. No. No.
Allowing users to change the language specification and side effects on a per-file, per-project, per-anything basis is a terrible terrible terrible idea.
"This is all covered in Knuth, and we don't have time to go over it again."
There are no "built in" operators in Haskell, other than " ", which is function application, and which cannot be overridden. Additionally, any "infix operator" can be used in prefix form, by surrounding it in parens - and any function name can be used in infix form, by surrounding it in `backticks`.
All other operators, like +, -, $, <, <$>, >>=, are defined in libraries (specifically in Prelude, the "standard library") - these operators cannot be overloaded in ad-hoc manner as operator overloading is done in other languages (bar qualified module imports) - to make use of one of these operators you must implement an instance of the class which contains it, such as Num for +, -. There's also the requirement to implement fromInteger, signum, negate, etc in Num. (If you can't think of a valid "fromInteger" implementation for your custom type, it's obviously not a Num). Also, some classes have associated laws which should prevent you from using them incorrectly
Admittedly the class/instance scenario could be improved with further checking of these "laws", but that would basically require a full theorem prover baked into the language - something that Haskell will probably get sooner or later.
There's still what I would consider "operator abuse" in Haskell - it's not that of overloading existing operators, but that of introducing new operator aliases for virtually every function in your library, as http://hackage.haskell.org/package/lens-4.1.2/docs/Control-L... does (yuck).
A nice convenient feature of Haskell is that you can scrap the official Prelude library (-XNoImplicitPrelude) and roll your own, as some others have done (e.g, http://hackage.haskell.org/package/classy-prelude). This allows you to effectively "clean up" some of the warts from the early design of the language, so it can continually improve - rather than needing to invent a whole new language when we decide it's not what we want. Num is an example of a class which gets lots of stick, because we'd often like to implement either of addition or mulitplication, but not both.
Doesn't Go have constants (const) which are immutable? What am i getting wrong here?
Go is a tool in your kit like any other language. You can't blame the architects for not providing an end all be all solution for every person's needs 100% of the time.
and yet it goes down once it is posted on HN. I have had some articles of mine end up on HN and I never went down, even when my blog was still WordPress hosted on a machine of mine.
This is probably more of a shortcoming of the various cloud providers than of the language/environment itself I guess.
In reality, do use something like WP Supercache. It will save your hide.
The "Retry for a live version" button is powered by Cloudflare, which also uses Go for many of its core services. So I'd be willing to bet it's the programming environment and/or the particular program, not the language.
If you just let it hang, the Cloudflare cached page should kick in.
No, Go's solution to generics is not interface{}. The moment you say that, you have lost. You are trying to fight Go and make it a language that it is not.
Always remarkable that such critiques always focus on the utterly trivial, while absolutely ignoring things like concurrency or composing complex systems. As always, the color of the shed is what the laymen want to argue about.
How do you make a custom, generic data structure without syntax overhead? I have not seen any counter proposal to this aside from "maps should be enough for everybody".
How do you avoid the noise from not having operator overloading or a similar alternative? This, again, goes unadressed.
What are the succint alternatives to functional abstractions for quickly processing collections of data?
"Just use a channel" doesn't really ring like a reasonable alternative to these questions.
In real-world code, the need for generic data structures is shockingly uncommon. It really is. This requirement exaggeration comes about by people acting as language tourists, building amorphous code of uncertain purpose, where things like "I'm going to sum up a bunch of unknown objects" seems like a serious need.
For most people who find Go to be a compelling language, it excels for practical, real-world needs.
I have heterogenous priority queues where I want to push in JSON data and plain strings, I have custom iterators, concurrent data structures, default dictionaries, etc.
Seriously, look up Python's itertools and data structure modules and realize that there's a wealth of things that are useful and practical and, above all, reduce code size while preserving interface contracts and semantics. Go is completely unsatisfactory in this regard.
Haskell holds your hand and checks more things for you.
Haskell code runs from two times, to five times faster for CPU based code, and lets you scale to insanely higher concurrent workload in a safer way.
Why Go? Because marketing.
Smalltalk uses less code to do the same thing.
Smalltalk lets you offload bookkeeping to the runtime.
Smalltalk code often runs faster for actual business workloads.
Smalltalk lets you add features faster with fewer bugs.
Why Java? Because marketing.
But doing this is was a waste of community time and energy. A better thing to do is to build cool stuff.What is the solution?
While I do agree that Generics can open up a whole new dimension of programming concerns. I think they are worth the additional syntactic complexity, because they allow you absolute accuracy when it comes to types. If we as a programming community want to ever get to the point where we have provably correct programs, or even reasonably correct programs, clear definitions of functions for an exact set of types is a necessity.
There are more synchronization features than channels in Go. Channels and switches solve most problems very well. However when another synchronization method is just simply required, check out: http://golang.org/pkg/sync/
Repeatedly, Go chooses the latter, and many people hail it while writing programs that crash on nil dereferences or duplicate their code for various basic types.
Here's the thing about the "Go sucks because Haskell is the best language ever" retort: Haskell has been around for decades longer than Go. It has made essentially zero impact, and even for the case of many of those who use it as the "my big brother" comparison against Go, it isn't a viable part of their daily toolset.
It's a theoretical solution that just makes for a nice checklist comparison against Go. You know this is true. We all know this is true. And everyone goes back to Java or C# or whatever else is your daily driver.
Yet people are making Go their daily driver. Solutions are being built, en masse, in Go. People are having great degrees of success with Go.
Isn't that weird? Might it be that Go adds primitives in a way that makes them usable and intuitive, without becoming strictly theoretical?
So people can keep posting these "Haskell, which I don't actually use in any credible way, is way better" articles, but they simply miss the point. They really do.
But generics are a fundamental tool to solve concurrency or composition. How do you propose to compose complex systems when you can't abstract on the type? How can you add new concurrency constructs that work safely for every type without generics?
Maybe if Go was dynamic or with full type inference, will like it more :)
I bet is great for the niche between C++ and Java, but not sure if I would want to use as a general programming language
http://snapframework.com/docs/tutorials/snap-api
main :: IO () main = quickHttpServe site
site :: Snap () site = ifTop (writeBS "hello world") <|> route [ ("foo", writeBS "bar") , ("echo/:echoparam", echoHandler) ] <|> dir "static" (serveDirectory ".")
echoHandler :: Snap () echoHandler = do param <- getParam "echoparam" maybe (writeBS "must specify echo/param in URL") writeBS param
-----
Rust (with third party library)
https://github.com/chris-morgan/rust-http/blob/master/src/ex...
//! A very simple HTTP server which responds with the plain text "Hello, World!" to every request.
#![crate_id = "hello_world"]
extern crate time; extern crate http;
use std::io::net::ip::{SocketAddr, Ipv4Addr}; use std::io::Writer;
use http::server::{Config, Server, Request, ResponseWriter}; use http::headers::content_type::MediaType;
#[deriving(Clone)] struct HelloWorldServer;
impl Server for HelloWorldServer { fn get_config(&self) -> Config { Config { bind_address: SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: 8001 } } }
fn handle_request(&self, _r: Request, w: &mut ResponseWriter) {
w.headers.date = Some(time::now_utc());
w.headers.content_length = Some(14);
w.headers.content_type = Some(MediaType {
type_: String::from_str("text"),
subtype: String::from_str("plain"),
parameters: vec!((String::from_str("charset"), String::from_str("UTF-8")))
});
w.headers.server = Some(String::from_str("Example"));
w.write(b"Hello, World!\n").unwrap();
}
}fn main() { HelloWorldServer.serve_forever(); }
-----
Go (native)
package main
import ( "fmt" "net/http" )
func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:]) }
func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) }
-----
Yeah, ok.
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
What's the point here?-----
Haskell (with third party library)
http://snapframework.com/docs/tutorials/snap-api
main :: IO ()
main = quickHttpServe site
site :: Snap ()
site =
ifTop (writeBS "hello world") <|>
route [ ("foo", writeBS "bar")
, ("echo/:echoparam", echoHandler)
] <|>
dir "static" (serveDirectory ".")
echoHandler :: Snap ()
echoHandler = do
param <- getParam "echoparam"
maybe (writeBS "must specify echo/param in URL")
writeBS param
Rust (with third party library)https://github.com/chris-morgan/rust-http/blob/master/src/ex...
//! A very simple HTTP server which responds with the plain text "Hello, World!" to every request.
#![crate_id = "hello_world"]
extern crate time;
extern crate http;
use std::io::net::ip::{SocketAddr, Ipv4Addr};
use std::io::Writer;
use http::server::{Config, Server, Request, ResponseWriter};
use http::headers::content_type::MediaType;
#[deriving(Clone)]
struct HelloWorldServer;
impl Server for HelloWorldServer {
fn get_config(&self) -> Config {
Config {
bind_address: SocketAddr {
ip: Ipv4Addr(127, 0, 0, 1),
port: 8001
}
}
}
fn handle_request(&self, _r: Request, w: &mut ResponseWriter) {
w.headers.date = Some(time::now_utc());
w.headers.content_length = Some(14);
w.headers.content_type = Some(MediaType {
type_: String::from_str("text"),
subtype: String::from_str("plain"),
parameters: vec!((String::from_str("charset"), String::from_str("UTF-8")))
});
w.headers.server = Some(String::from_str("Example"));
w.write(b"Hello, World!\n").unwrap();
}
}
fn main() {
HelloWorldServer.serve_forever();
}
Go (native) package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
Yeah, ok. like
this