Twelve Years of Go
go.dev
go.dev
It has also ruined other programming languages for me. "go get" doesn't print 30 lines of text telling me that a new minor version of "go get" is available, and that I should stop what I'm doing, rm -rf node_modules, upgrade it, and then resume what I'm doing. It just pauses for a bit, and then I have the library. (I also love reading about the node community's push to make installing libraries not run arbitrary code on your machine. Yeah, I've been doing that for years with Go. It's great. I can use a library and it can't print a "hire me!!!" ad at install time. What an innovation!)
I also remember struggling for years with not being able to run other people's software. There was an RPM package, but not a Debian package, so I have to build it from source. ./configure; make; oh no, the c compiler I have can't compile this code. With Go, you can just emit a binary for every supported platform dump the binary somewhere, and everyone in the world can download it and run it. No installing packages, no finding the right version of Go (that doesn't exist in your Linux distribution because they never ship up to date versions of programming languages). Just software, running, forever.
It's really good stuff. Go is the tool that lets me make software, and not worry about bullshit. And that's revolutionary, even 12 years later.
Which is also the hardest part of convincing people to use Go for me: "Why can't I just .map()/.filter()/.find()?" followed closely by "Why do I always have to check for errors?"
What is odd to me is that while yes, my Go code is more verbose than my node services - I always end up writing less Go for the same thing.
if err != nil { return err }
IMO if Go didn’t have its tooling, no one would care about it.
every if err != nil; return err let's me mentally draw a line in the sand and not worry about exception handling for code above that line. It lets me start fresh and restart my mental model with the line of codes below the error handling block.
it doesn't take years of writing Go to understand this, all you need is a open mind to how Go does things.
My code is almost exactly:
err := doThing()
if err != nil {
return err
}err = doAnotherThing()
if err != nil {
return err
}etc.
There's no need for me to "start fresh". Each line of actual stuff doing might return an error which needs to be returned. That's it. It's a complete waste of space and inhibits readability to absolutely no benefit. And this is extremely common across our code base.
I'm far from a Go expert, but I feel like this line is a bit pointless, especially if you write it a lot. At this point, why not just not handle the error, or panic?
At high scale, you want to perhaps try your query a few more times, backing off exponentially, maybe even round-robining (or more complicated load balancing) among different targets. Throwing up your hands and 5xx-ing a request that easily is not something you can afford at high scales of traffic where small outages happen _all the time_.
so basically you mean that this only applies to like 0.001% of all websites/apps.
thus it's stupid to do it. I mean even than you would have an error that you need to bubble up or circuit break it somwhere but probably not at this layer.
also KISS and MVP, never ever overcomplicate something when you do not know anything yet, so most people don't need to built for scale at day 1 and it also is stupid to do it.
Let's say you've got a function that reads from a file. If the file doesn't exist, what do you do? That entirely depends on the context the function is called in. If it's in a web server, you might return a 404. If it's a background task polling for some data, you might sleep for a while until the file is uploaded. Or you might want to create the file yourself.
if res, err := actually_important_bits(...); err != nil {
return nil, err
}
The actually important bits are hidden in the middle of line noise. In the "common case" where `actually_important_bits` is just a simple function call it's not necessarily as bad, but the problem is when you have ten successive instances of this and one is slightly different. It's impossible to notice the important difference at a glance.For an industry that is just starting to understand that code is read hundreds of times more often than it's written, golang fails at the few things we actually know for certain about what makes it easier to understand code at a glance.
res, err := actuallyImportantBits(...)
if err != nil {
return nil, fmt.Errorf("actually important bits: %w", err)
}
And other times you have to do this: if err := actuallyImportantBits(...); err != nil {
return nil, fmt.Errorf("actually important bits: %w", err)
}
The problem here is that you really don't want "err" to leak to the outer scope, so the second case is preferable from an absolute reliability and least-surprise perspective... but you can only do that in certain arbitrary cases. I think it's a bit of a wart.You can certainly handle "res" in an else block, or even write "err == nil" and handle it there, but that is surprsing. I would say it's simply not done, ever, but the Go codebase itself does it (src/go/parser/interface.go.ParseDir was the first example I found; but my search returned many screenfuls of candidates so there are probably more cases lurking in there).
The fact that you have a choice is not ideal, basically.
But, having actually important bits in if err := ...; err != nil {} blocks is not detrimental to readability. You will know how to read that after 5 minutes of reading any Go program.
res, err := ...
if err != nil {
return nil, fmt.Errorf("...: %w", err)
}
for that exact reason. This doesn't scan any worse than any other text-based code. (Page in the people selling visual programming here.)One of the things Go taught me is that I was not being as careful about my errors as I should be. It can be argued that exception-based handling provides you a nice baseline default, but it makes it way to easy when doing network or system-type programming to thoughtlessly default to that, when you need to be thoughtfully defaulting to that.
With sufficient care, exception-based programming and errors-as-values converge in the end anyhow in "code that treats errors correctly". But my exception-based code is a lot more informed by the errors-as-values approach now; a lot more try statements with catch statements that actually do something.
Even Haskell's very nice Either monadic handling can make it too easy to be in the heat of the moment and not thinking about what the errors actually mean and what I can do about them.
I don't think it's appropriate for every domain, which is why I qualified the code I tend to work on. But in those domains I'm thinking a lot more about how every single line of code can go wrong rather than leaning on default exception-based handling and expecting it all to work out.
I identify with this so much. Especially when dealing with external things (file system, database, network) things can go wrong at nearly every step. And yeah, that means you have to check errors at every step, but it forces you to think about how you want to handle them, and what message you want to propagate when they happen. As a result, my Go code has very few unexpected errors in production.
Handling errors everywhere means problems are already solved before they happen. No 1 am pagerduty alerts because we didn't consider what would happen if a DNS server hung until we timed out and thought just wrapping in a try/catch and crashing was a good idea.
To get into a situation where you'd need to handle n! cases, you'd need to keep running the statements after a failure, and then collate and return all the errors at the end.
Not sure why you'd want to do that. You'd definitely need to go out of your way to do something like this, and probably start asking yourself why you're doing this pretty early on. Plus it would flat out refuse to compile in some cases where there are dependencies between the statements.
{n + 1 \choose n - 1}
What code are you writing that results in this set of possibilities?There is no hard technical line between "unit test" and "integration tests", it's a semantic question of how you define your units. Even if do you take a tiny, restrictive definition of your units, you could still use a fake or stub instead of a mock.
https://martinfowler.com/articles/mocksArentStubs.html
To get very specific for Go, we use testify suites, tend to set up fully functional stubs in `SetUp`, and then test cases either use them to verify happy paths, or `s.BreakStep1()` in one test, `s.BreakStep2()` in the next, etc. So in this case we would write a total of five extra lines for the five possible ways to break.
You can successfully build huge chains of code that are just blindly passing errors up without adding any context about where they happened or anything in a way that even Rust can't compete with.
Haskell mitigates this issue by also having one of the more clever ways of dealing with errors, if you start getting into monad transformers or some of the advanced stuff, so it's not all bad. But it definitely can make it so easy to "handle" errors that you just forget about them.
I see a lot of the same issues in Rust code today FWIW. People just keep bubbling up errors and at the toplevel say "fuck it" and dump them, without _actually_ building a reasonable error chain to offer the programmer a story behind how the error happened. The fact is, error handling in any language is tedious. Whether you do it with a sum type, a product type, or Go's error values, either way there's going to be lots of verbosity and boilerplate.
a, err := foo() // oops, unhandled error
err = bar()
if err != nil { ... }
or fmt.Println("...") // oops, unhandled error
or more insidiously err1 := foo()
if err1 != nil { ... }
err2 := bar()
if err2 != nil { return err1 } // oopsThey do, they throw exceptions.
> In the first and the last case, it seems obvious to me where the error is
The last case is especially insidious. I've seen it in production several times now. Very easy to miss. Particularly when refactoring/copy pasting code (which you have to do a lot of in golang).
The whole point of a programming language is to make the programmers life easier.
By now decades of exposure to programming languages have made try/catch the standard way of working with errors. Forcing the programmer to guess issues, when the compiler/runtime could be doing it- IMO is just plain waste of human labor. And for even medium to large applications is a pointless exercise.
let _ = openFile()
Error ignored, it does compile, it will probably ends badly.
As for network error: https://pkg.go.dev/net#OpError
Go would benefit a lot more from some basic slice manipulation tools compared to features like generics that have actually made it into the language.
The error handling I don't find so frustrating - it's great that it explicitly marks at the call site which functions can potentially error. It's like a working version of an inverse noexcept from C++. I do wish they would take a leaf out of swifts book though, with the try keyword. In practice error handling flow in my go programs is identical to using exceptions, it would be nice to have some helpers to make this default less verbose without losing the ability to distinguish at the call site which calls are error-y.
If Russ Cox ever proposes to rename Go to JavaScript, I guess no one would complain. ;)
It isn't the only difference between the two, but I think it would have consumed enough of the oxygen of the niche Go is currently in that Go might never have been born.
In practice, I find Go to be just slightly harder than working with dynamically typed languages, rather than a huge step, and the benefits I get in return make me prefer it for almost any task above 200-ish lines. I definitely can not say the same about Java, because of this difference and the second-order effects it has on the entire ecosystem.
It is still completely practical to create a production-level Go project by just cracking open a text editor and typing "package main" into your editor and typing away. I get the impression most people would not consider that a practical way to start a production-level Java project.
As for your last paragraph, I feel like we often mean something different between a production-level go and java project. Non-IDE java development is entirely possible, but I think a prod project usually means something much larger than it does in case of go.
I struggle to think of one that has risen to the heights Go has risen.
I'm a computer language polyglot and a bit of a language tourist, though not as much as some people. There's a huge churn of features out there in some language somewhere, that has never manifested in any top-level language like C++ or Java. (For instance, array-based programming has been experimented with quite a bit, but has never been in a top-grade language. The closest that I know of is NumPy.) Whether Go is a top-level language or not at this point is a matter of legitimate debate (depends a lot on your exact definition), but it's certainly knocking on it.
The closest I can name are things like Python, but there is a fundamental difference between run-time duck typing and compile-time interface conformance, although they're certainly related.
A lot of people make a lot of fuss over how fast the programming world moves, but I'm a bit of a contrarian on that. There's a huge amount of churn at the very small scale, but when you get to that top-level set of languages, we're actually very conservative. For pete's sake, C is still a top-level language in 2021! It's finally on its way down, but it's got a long way to go to fall out of that criterion, unfortunately.
This is why I didn't even necessarily label Go as a "top-level" language. It's only 12 years old, after. It's a whippersnapper of a top-level langauge. 25 years old makes for a young top-level language!
How do you evaluate that?
I'm a little lost by what you mean here? In my mind the only difference between a Go interface and a Java interface is Java lets you declare them in the class signature.
That means you can't just take an image class from some JPEG library and declare an interface around its already-existing methods. That means the JPEG library has to know all the interfaces that may be useful, and declare them all first. If some of those interfaces are from other libraries, it must depend on those libraries to do it. This pressures image libraries to get together and have to declare "image processing" frameworks, which creates pressures to create all-singing, all-dancing image frameworks because these new interfaces being declared have to work for everything up front. If you get the interfaces wrong, the end-user of these libraries can't just fix them up on the fly. The framework then is pressured to undergo significant churn as it keys in on the correct all-singing, all-dancing set of interfaces to provide, either breaking backwards compatibility or having to drag along every bad decision it made for extended periods of time.
Granted, if a set of libraries does successfully run this gauntlet, the end result can be quite impressive, but it's a hell of a gauntlet to run!
This is also why it's at least a modestly acceptable Java practice to pre-emptively declare an interface for anything you think you might need an interface for later, because if you don't do it now, you'll have a harder time coming back and doing it later. I have a Java code base where darned near every class is basically duplicated, as both an interface and an implementation. I understand not everyone thinks this is good practice, but the language still pushes you in that direction even so. In Go, it simply neither good practice, nor something the language pushes you towards.
In Go, if I need to parse PNGs, I get a PNG parsing library. It just parses PNGs. The author of the library can make the best PNG library they care to, and the author of the library has no obligations to pre-declare any interfaces. If someone wants to weave this into a metalibrary, they can, and they don't have to fork the PNG library to do it, they can easily declare interfaces as they like, wrap things if they like, whatever. It's all more flexible. You're less likely to end up with that best-of-breed, all-singing, all-dancing awesome framework that is integrated and does everything in the end... but in the meantime you also get to use all the code that would have failed to finish the Java gauntlet.
In Java, because interface declarations must temporally precede all implementations, there's this huge pressure constantly pulling things into huge, all-encompassing frameworks, because all requirements are constantly being pushed up into the interfaces... the same interfaces that also have to exist first, before they can use them.
On paper, this is such a small little difference. It even sounds good... "why, of course we should have to declare conformance to interfaces? What if we accidentally implemented an interface and all hell broke loose? [1]" In reality... it's been a huge mistake.
[1]: My answer to that, BTW: http://www.jerf.org/iri/post/2954
This is of course not to mention the dangers of unintentionally implementing and interface and having bad things happen (this happened in the golang stdlib out of all places as I recall).
Languages like Scala with HKTs or Kotlin with delegates (if I'm not mistaken) solve the issue of delegating to interfaces without much boilerplate. It's just that golang authors have not been exposed to other languages since the 70s.
Not to mention it has sum types and pattern matching, something not available in golang. golang doesn't even have proper enums, quite astounding really.
Also, Go most definitely has a runtime, what runs the GC otherwise?
That's an awfully restricted definition of "runtime": https://golang.org/src/runtime/
Interestingly, what made me go through similar evolution was the very language in which I was trying to do all those things, namely Scala. After a few years of trying to be "smart", I realized that the problem was usually bigger than the language.
So perhaps, it wasn't Go, nor Scala, who helped us in our realization, but life and experience?
* Static binaries by default
* Single, straightforward build system (no DSLs)
* Single, ubiquitous code formatter
* Minimal learning curve
* Zero-work package publishing
* Zero-work documentation generation and publication
* Testing framework out of the box
* Production-grade HTTP server out of the box
* Low latency GC out of the box
More generally, C# and Java have always seemed to have a philosophy of "make everything as abstract and configurable as possible, and make the user understand every configuration option in order to do anything (overwhelm the user with configuration)". Granted, I haven't used C# or Java seriously since Go was open sourced, so it's possible that these are among the things that improved in C# and Java following Go's release.
For me, Go being combination of being well-thought-out, opinionated and batteries included took away the futile fanboi flamewars/bike-shedding: JBoss or WebSphere? Tabs or spaces? Struts or Spring?
For these reasons and more, Go is offers a more pleasant experience when working in a team. When reading code other's wrote,I encounter fewer surprises in the logic and project structure. Go codebases are easier to grok, IMO.
Does this hold true? Don’t you need to switch to musl or something, to build a static binary?
So yes, your comment is probably right, but I get the impression the grandparent was a tiny bit tongue in cheek anyway
This happened to me too, without using Go. I think I just got older.
Until your users realize that if there was a security vulnerability which was fixed, a system upgrade is not enough. They will have to either hope that you haven't moved on, or build things themselves. But then, thats not a problem with Go specifically, thats a general issue with "static link all things".
Exactly. Which is why I don't get the "static linking is the best solution for deploying applications". You need to be able to do both. For example when building a C/C++ application you can decide if you want shared libs or static builds.
IMHO Go certainly chose wisely when it left out many OOP features of questionable value. And perhaps in doing so, it avoided the whole OOP culture, which has produced a lot of over-complicated software and tools. The culture of simplicity in Go is a really good thing and worth defending. However, we should be open to the idea that one or more additional language features might help to further this goal.
As far as binaries, I think Rust beats it out here too. Take path separators for example. It’s completely possible to have a binary in Go that uses the entirely wrong path separators for the OS. Rust forces you to handle this.
These aren’t true. There is true versioning and no assumption of GitHub. Shouldn’t this be a complaint about the assumption of crates.io?
> No installation-time execution either.
This is also not true. There is no installation-time execution.
As it should be.
You name any Go package based on a URL you control (and you can refer to any underlying source control by returning appropriate metadata from that URL). Package names that are URL-based is an arbitrary decision, but it seems like it at least solves that problem. Personally I’m much more a fan of that, since otherwise you need to put far too much faith in a single provider (crates), and enable a whole class of attacks and ownership squabbles. Better to just punt this to the already-solved DNS and web ecosystem. I just can’t agree that a single centralized repository is “as it should be”.
No, I _like_ crates.io because Rust is very explicit that that is where the packages come from. We can get into the benefits and risks and whatever about centralized vs decentralized package managers, but that’s not what I’m talking about. I just want to know how Go does what it does so that I can code confidently in it. A lot of Go packages are specified like so:
go get -u github.com/username/repo/version
But this is not enforced (you don’t have to specify a version) and this is also not a valid Git repo path and where exactly is this dependency stored and I can go on and on. When you import this package it’s usually
import “github.com/user/repo/version/module”
But then there is not always a <module> directory in the repo and… you get the idea. This sort of stuff hurts my head and I get it that Go is maybe trying to appear simple but this black box handwavey stuff can and will burn you (this very reason is why the Go community is generally against frameworks) so I just want to have a simple, clear answer and it seems no one else in the Go world has any of these questions. This turns me off.
I’m confused by your last bit. Neither Rust nor Go have installation time execution and this is good. I was referring to how you can’t just say “Oh Node has it and this is bad but Go doesn’t and this is good” because Rust doesn’t have it either.
Re: git, there is no assumption of git. Go also natively supports svn, hg, bzr and fossil. You also have the option to vendor things.
It’s fine to favor crates because it’s closer to what you’re used to, but I think you’re just complaining about ergonomics. They both have semver and implement satisfiability in similar ways (AFAIK).
It seems like the source control mixin is what’s causing the most frustration, and I get it — that’s where you have ergonomics you’re not used to — however, this is also where Go shines since it essentially gives you supply chain integrity without the need to trust any users uploading code (module owners) or third party vendors (crates).
What is the question for which you are looking for a simple, clear answer? Honestly, the documentation is quite excellent [1], but I’m happy to do my best to point to the best place for answers.
No inheritance - no more digging through the massive world-tree of objects to find the code that actually does things.
No churn - I have not seen a Go update break my code in about 8 years of use.
No complexity - I like the culture of simplicity and eschewing dependencies in favour of writing the minimum code required.
No dynamic libraries - deployment is easier and apps more stable
No declared interfaces - they are defined at the point of use, not declared elsewhere
No header files - why C++, why?
No implicit type conversion - of the kind that plagues JS (see WAT), this rarely makes it more verbose.
There are of course a few gnarly corners - nils, errors, panics, struct tags are not very satisfactory IMO at the moment.
There are also lots of great positive things about it – the GC, tooling, fast compiler, stdlib and docs are a great example for other languages IMO.
I'll be really interested to see where they take it next, while hopefully keeping the culture that has made it so pleasant to use. Thanks to everyone working on Go from me, and here's to another 12 years of Go.
* No DSLs for declaring dependencies or otherwise scripting the build system.
* Excellent standard library
* Incredible ecosystem
In all cases, these issues seem positively trivial compared to "you can't parse JSON or send an HTTP request until you learn some DSL or cargo-cult someone else's build file".
There's a couple of struct validation libraries that got IMHO a bit overexcited with what you can jam in a struct tag and then interpret, but they don't seem to have gotten very popular, so it doesn't factor into the language much.
https://github.com/golang/go/search?p=4&q=struct+tags&type=i...
Personally I think the language would be better without them, but it's too late now.
Re build directives - the complaint is they are comments which do things and change code/compilation, the syntax I don't care about, but I do care that they've abused comments to do this.
I agree, these problems are pretty trivial, I don't lose sleep over them.
You still have interface methods? I had problems navigating a new codebase and find the places "actually doing things". Some object was passed in somewhere which mysteriously implemented a one method interface defined on the spot in the other go file. I.e. the implementation had no relation to the interface which was obvious without a lot of searching and finding the right implementation.
Also passing in functions (callbacks?) all over the place is a little messy at least for a newbie. It was hard to find where the functions where called and at what point and how the program flowed.
(this is hard to explain but maybe somebody gets the point...)
edit: somebody else touched on what I also meant: " duck typing make refactoring and understanding new codebases error prone"
Also the modules and dependencies management surely is a joke? Pulling stuff from github willy-nilly? Quite bad in any case when compared to maven where you have a local repository with all the dependencies (so they don't change or disappear from the internet so that you can actually build your software 5 years later, exactly in the same way)
IMO interfaces are best used sparingly and in a minimalist way like io.Reader (but I prefer them to Java interfaces and have not found them confusing nor felt compelled to find all concrete types conforming), callbacks are best avoided if possible, and yes dependency management has only recently improved.
That's not 100% accurate; as a concrete example, tell me which files (to say nothing of the actual downstream types!) contain the implementations of this interface method: https://github.com/kubecost/cost-model/blob/v1.88.0/pkg/clou... (err, without using github's fancy new SourceGraph-lite integration, of course, that'd be cheating)
I find the sibling "No declared interfaces - they are defined at the point of use, not declared elsewhere" similarly suspicious, but suspect we're having a nomenclature mismatch
But why? I've often wanted to know what a method does in Ruby and have had to resort to .method(:x).source_location because it is so dynamic only the compiler knows once it has finished running it. I've never had to find all the places that conform to an interface in Go (a very different question) or Java, because that's what an interface is for, so that you don't need to know, and new people can come along and conform too: your interest should be limited to what they can do, which the interface tells you already. Maybe this is a problem in getting to know a large complex codebase I guess? I've never encountered it in the real world.
The second point is linked - interfaces are used the way you describe in a few other languages, Java among them, (find me all the implementors of x), but not in Go, the whole point is you have no idea who the implementors of an interface are, new ones will arrive, and that's ok.
It's certainly possible to write bad, confusing and enterprise Java flavoured code in Go, but the lack of inheritance at least does away with a whole bag of hurts related to overabstraction.
Think about interfaces like io.Reader - why would you want or need to know every implementor of these?
That's a very idealistic perspective, and my sincere congratulations that every codebase you've worked with so far has been so great as to completely and unambiguously document every edge case and pre/post condition.
If we stick just to the cited example:
Features() string // Features are a comma separated string of node metadata that could match pricing
great ... so I'm guessing if there are no such features it returns "" then, but otherwise it ... just contains the metadata keys? key=value as CSV? It escapes any "," found in the values with \\, does it? What's an example? Well, normally I'd go look at the implementations but in this awesome world of fully specified godoc I guess I shouldn't worry myself with such detailsI'm almost sorry I replied to this, because we are clearly living in such different universes, but I am actually genuinely interested in reading the URL of the godoc you've experienced that is so perfect that one need not ever bother with how many disparate implementations there are
This interface is not great as it asks for ambiguous info and three methods.
I'd look at the docs, and what the callee does with .Features() for guidance (which in well written code will usually be in the same package as the interface, ideally the same file), not what one implementation happens to do - otherwise what's the point of the interface as you're coding to one implementation?
So I guess my answer is a variant on 'No true Go programmer would use interfaces this way', genuinely sorry about that, as you say we probably live in different worlds - I don't work on kubernetes or things inspired by it. If this is a big problem for you though, I reckon tooling could solve it for you, as you pointed out.
Plus, you get the performance of a compiled language, with a simple syntax. Sure, you get just slightly better results with C/C++/Rust, but then you deal with complicated OS level calls, memory and library deployment issues (problems fixed by Go). Yes, a few benchmarks show C#/Java almost as fast, but at the price of a highly optimized syntax not seen in any average programmer. An average guy get superb performance with Go without complications from day 1.
And absent object oriented features are quickly forgotten.
Ironically the canonical Python type checker, code formatter, etc take ages to run on even small code bases.
What actually increases JVM startup time is class loading, as it has to do byte code validation and the like for each new class. This is only apparent for largish frameworks though.
As for JIT, there is no much point for short-lived programs. Like, most python scripts are run without that and people write prod code in it.
On this low-end Chromebook (Samsung Chromebook 3 with a Celeron N3060 @1.60GHz) I can start the JVM, load the classes for my CLI program, and print a help message,
jpavel@penguin:~$ time rcr -h
Usage: RCloner <config path> get|put <entry> [args]
RCloner <config path> list
real 0m0.316s
user 0m0.208s
sys 0m0.126s
in less than 1/3 of a second. And this is with stock openjdk version 1.8.0_302, which doesn't include the startup time improvements of Java 10 & 12.Sure, I wouldn't write utilities meant to be piped one into another, but for standalone CLI tools, the JVM startup time isn't prohibitive at all.
What OS-level calls are you doing in C++/Rust that you aren't in Go?
> library deployment issues (problems fixed by Go)
How is Go's library tooling better than Cargo? I believe Go's is strictly worse, with its URL-based imports and how it deals with major versions.
As for go mod, yes it's not perfect but it's as powerful as Cargo. https://golang.org/ref/mod
This personally helped me build a good foundation on Golang.
https://www.youtube.com/watch?v=jTjRGe0wRvI&list=PLVrpF4r7WI...
From there, I started reading about it more seriously here: https://golangbot.com/learn-golang-series/
And I've been using it and loving it ever since. There are one or two things that trip me up (slice manipulation can sometimes get me if I'm not paying close attention to my capacity and just pointing around, rather than copying) But for the most part, it's a fairly elegant language, and amazingly fast! For me, it's also been incredibly intuitive start working on asynchronous features.
The new inclusion of Generics is just icing on the cake.
However, I always feel exhausted when implementing real-world systems with Go given the lack of $things (that everyone feels is a virtue). Over time I realized that a lot of people just aren't as lazy (or scared of breaking things) as I am - they find it easier to copy code dozens of times and then fixing them all in one go using their ninja refactoring skills. Just a different kind of tradeoff, at the end.
So given how laborious it is to make anything more than simple programs (because of the amount of copy-paste-driven-development required), I generally avoid Go unless I'm writing a webservice.
For me Go's virtues are static typing and wide variety of community packages to do things. The whole "oh not having features is a feature" thing is just an opinion for the sake of having an opinion. otoh, I damn excited to have generics support soon finally :)
Either you're not using the tools Go has to their full effect, or, possibly, you shouldn't have chosen Go. But I make that last concession not because it probably fits your case, but because it is technically true. (In particular, don't take Go for heavy math code where you need a type system that is ready for lots of mathematics.) But it's probably not applicable.
You should not be copying and pasting all the time.
There are several communities; I happen to hang out on the reddit /r/golang. If you've got something that you'd like to see how to refactor to not be copy and paste, consider posting a question there (ideally with a running version in the playground of whatever you're asking about). It is true that not everything can be improved, but most things can.
The language is extremely weak (it's not expressive), which translates to overly verbose code that is difficult to traverse. Logic that can be expressed in a couple of lines in Java becomes 10+ lines in golang, with code scattered everywhere. Not to mention that golang lacks enums or sum types (the latter have now made it into Java), which are a huge safety and productivity booster.
The problem is, a lot of people are used to working in languages which have an abundance of features, so when they have a problem, they have learned to reach for the feature that solves it. In Go, you have fewer tools, but they are sharp, and generally well-chosen and work together well.
"Go doesn't have the feature I'm used to using to solve this problem" is not the same as "Go doesn't have a decent solution to this problem". If you are constantly copying and pasting or spreading things out in a way you don't think you should have to, run through the tools that Go does have again. There are several techniques that aren't going to be the first things you necessarily reach from from another language, but work just fine in Go. This is not a complete list but it gives several examples of such techniques: http://www.jerf.org/iri/post/2945
There are some things it really can't do. (Again, I just can't understand the people who are trying to jam their mathematical code into Go. It's just so bad at that.) But that set is smaller than the critics think, because they confuse missing features for missing solutions. It's just another variant of "don't write X in Y", which is never a good idea.
And again, I invite you to post any such issues you may have to /r/golang. If I happen to pick it up, I won't be afraid to tell you straight out there isn't a good Go solution to that. I've done it before. But that happens less often than you might think. I also remind you my goal will be to come up with a good Go solution to the core problem, not "the closest approximation to the feature I expected to use" or anything like that. Write Go in Go, not anything else.
If statements used for error checking are a bit verbose but basically fine.
I'm weakly pro-if, but no, it's not. We went a lot of years without it, and some rending and gnashing accompanied its introduction.
Should you avoid if-statements? It depends. What are you going to have to do instead? You're going to have to do something. Is that something going to be more understandable for your co-workers for the lifetime of the code? Maybe, depending on your co-workers. Maintainability over the lifetime of the code far outweighs and "should" that they tell you at school.
People seem mad that they have to plumb around `err`, and that they have to provide useful context with fmt.Errorf. I see that as letting good programmers make good systems. The default in other languages is useless -- line numbers and arguments is all you are allowed to have, and when something goes wrong it takes up your entire screen with noise. Not as good as everyone thinks it is.
No 'oops I forgot to put in a try/catch and now my code died with no explanation'.
No 'I forgot a finally ( or didn't realize I needed one ) and now I'm leaking resources'.
No 'should I return Null or false or an error code?'.
No '20 log messages for the same error because every function is reporting it'.
The Go model
- Return err, always as the last parameter
- When you need more context, add it to the error before you return it
- There is a calling function that reports errors. Maybe main(), maybe a subscriber, maybe a goroutine. There can be other situations of course but the point is that there's a clear ownership. If someone is logging errors in a higher up method, they should be prepared to explain why in code reviews.
2. Defer is nice. As easy to forget as using in C#.
3. Always null/nil. Uncle Bob is plain wrong here.
4. Stack trace. But you should keep things wide and shallow. No matter what technology you use.
In Go it is about as easy to swallow errors as with try-catch. But my post was more about how all the if-statements generates more unnecessary if-statements.
This is literally the exact opposite of what I believe, and the bane of my existence at work. Wide and shallow code is spaghetti. Too many APIs = continuous confusion and relearning.
By default in Go uncaught panic go to stdout.
"That's the developers fault, not the languages"
Look, the old grey mares of the programming world are doing the best they can. I'm not going to blame C because its developers usually make it up as they go.
But we've learned things over the past 50 years, and one of the things we've learned is that company defined 'best practices' and code reviews can not catch all the mistakes that developers make and all of the things that can bring a service to its knees.
Go has the benefit of experience. It knows what mistakes developers make and it is going to prevent them from doing that. There is Right Way To Handle Errors in Go.
How many times have I seen uncaught exceptions? I saw one a week ago.
How many times have I lost resources because I didn't realize something I was calling could throw exceptions? Dozens.
Null/Nil exceptions. I couldn't count the null pointer errors I've had to fix in my time. Probably in the hundreds.
"should" keep things wide and shallow - somehow when Java 8 came out all the Lambda programmers lost this message.
None of these practices scale. We know that because we've seen it
Well unfortunately, not always.
There are too many ways too screw up error vars + nils + control flows.
This is so backwards. First, I want my program to immediately crash if I have a bug. Go is like shell in that it keeps going even if there's an error. Second, I'm used to getting stack traces, Go is the language that will give "no explanation" by comparison if there's a failure.
Re stack traces, they're fine I guess, but I prefer a well-crafted error message to 200 lines of irrelevant file locations/functions.
In practice it's impossible to exercise all the inputs your programs may get, and then they crash in production when users do things you don't expect.
Something had happened during the processing of this web request? Catch the exception and convert it to an appropriate status code.
You should only ever let exceptions fall through ”main” when the problem is really not something you can manage to handle.
In practice often people let the exception eater in main handle it, and it either logs somewhere nobody looks or returns this sort of generic error and exits:
https://www.google.com/search?q=Microsoft+Word+has+encounter...
An error being returned doesn't always mean there's a bug.
> Go is like shell in that it keeps going even if there's an error.
With both Go and shell scripts it's up to you if you want the program to keep going when there's an error.
The bug is not the error, the bug is the unhandled error.
I wish that one use case was handled better. It is just too easy to mess up.
I personally vastly prefer Rusts Result<T, Error> and Erlang/Elixirs {:ok, T} you pattern match on or crash the process and recover.
The code is cleaner while it also makes harder to make mistakes.
I prefer the current situation to exceptions but would like to see them try something more like Rust or Elixir at some point.
This.
Most people are used to thinking in terms of try/catch. Programs exiting on exceptions. This is just one of those things like Garbage Collection. Its one of those things a modern programming language should do.
The example is a bit like using automatic transmission cars. As much you can sing praises of a manual transmission cars(manual control, mileage etc) its just everyday programming is like driving in roads with heavy traffic, and whatever perceived poetic beauty a manual task could offer, the automated task works better if you have to do this for hours everyday.
In many ways a language without try/catch semantics these days is dead on arrival for most shops.
1) ridiculously easy built-in cross-compilation
2) structs (compact memory layout and usage)
3) easily having millions of cheap threads aka go-routines
4) modern standard library for things like cryptography
Things I hate about Go:
1) plugins (very painful to get working and not even cross platform - e.g. Windows)
2) duck typing make refactoring and understanding new codebases error prone
3) no ternary operators (the verbosity!)
4) missing basic collections (like set, various queues etc.)
5) lack of built-in memory use limits
6) errors and error handling (just give me a stack trace for pete's sake)
A lot to learn from this success story
1Password is also a heavy golang user, as a more silent entry into that race
If you want a framework, use Rails/Django/Node as they are very mature. Huge plugin ecosystems, great for prototyping non-trivial features like authn, because a plugin certainly exists for it.
If you want more control (fewer dependencies), roll everything yourself with Go. The built-in libraries are fantastic, you can spin up a CRUD app without any external libraries. There are also great third-party libraries, but I would stay away from framework-y stuff like GORM.
But it is still a framework, which means it is making a lot of decisions for you and forcing you to learn its own way of doing things. Ultimately it is a relatively thin layer over builtin Go libraries like `html/template`, `net/http`, `database/sql`; generally speaking, the Go philosophy is to build systems yourself from these components and therefore keep the architecture simple, focused, and maintainable.
Unless you are stuck with Go for a good reason, if you want a framework use one of the industry standard ones mentioned previously.
Building an API backend for a single page app though, absolutely.
Go is great for web services, it's the first thing I reach for.
I've used Rails extensively before writing some larger sites in Go. Quick comparison of Go vs Rails:
Pros: More performance, multi-threaded extremely capable web server built-in, culture of simplicity and low-dependencies, no breaking changes, goroutines, ideal for small services, static binaries (all deps included) so no need for rbenv, docker etc etc, no included JS, great stdlib (far better than Ruby's IMO), NO INHERITANCE.
Cons: No standard structure others are familiar with, you'll need to find/write code for things like migrations, auth, rendering views, skeleton code generation.
For things you need to find/write this may seem intimidating but it's an opportunity to explore the bits you liked about rails and jettison the bits you didn't like or need, and the stdlib includes a lot of what you need at a low level (e.g. html templating, crypto libs). I cannot emphasise the importance of no breaking changes, it's so refreshing compared to other language ecosystems like Ruby or JS.
Overall I'm really happy with Go for web apps and would choose it again in a heartbeat, particularly over Ruby and Rails (which I also like, but has performance issues and cultural issues IMO).
From your comment I think you're talking about a query builder/executor though, which is a specific part of an ORM, they're pretty simple to build if that is your thing or there are a few examples of that out there. You're really just building up an sql string, storing params, adding a few helpers for things like joins and then executing.
I personally use a query generator to generate consistent queries, and generated code per resource to create models from results.
I dont understand why they move forward with this. Go is absolutely awesome, it's a gem, adding generics is too risky. This is such a bad news for me (i didnt know). I'm trully affected.
is it less suitable for hard programs than other environments - almost certainly
Maybe it's a style thing, but I tend to have a lot more trouble with "WTF does this (leaky, inevitably) abstraction actually do and where does that actually happen?", when reading code, than with too much code.
Generics will be similar; people will misuse them, and you'll curse their names when you have to dive in and debug it. But it will also let good programmers write very good programs and libraries, and that's going to be a huge benefit for everyone. As we've seen with interfaces, they can be misused, but they can also be used correctly. Just look at the standard library for examples of how they work well. io.Copy() was written once and can work on buffered streams, disk files, HTTP bodies, ... anything! That's a good use of interfaces. We're going to see the same with generics, and it will make a lot of people's lives easier and more enjoyable.
Example: first you agree with me "its already easy to write bad code", well you agree then its gonna be easier. Your example about io.Copy. Yeah bingo, absolutely io is the exception, the only case I know in 25 years of programming that is made tasteful with generics. Actually its the only case I know in 25 years of programming where a diamond-like multi inheritance structure is okay. IoBase, IoBaseRead:ioBase, IoBaseWrite:ioBase, Io:ioBaseRead, ioBaseWrite. You get the idea.
Do you realise the language grammar is modified? They are modifying Go's grammar. Man, they gotta have some balls to make virtually a new language after 12 years of success.
Im open. I am. But the idea is bad on paper, now the signs are too.
The designers of Go recognized that generic type parameters are necessary.. it’s just that they decided to only bestow them on a few types in the standard library instead of designing a general solution.
Thats exactly the proper dichotomy. Those choices were made by great language designers, not by programmers. Generics are some type of macros, of course they are useful. In some rare, very sensible cases, where the added complexity is really worth it. In the hands of programmers eager to show how smart they are, they are deadly. Code reviewers all around the world are gonna be like "why dont you use generics here?" just because they can. Bloated code, everywhere.
Go was a niche language suitable for 10x programming. It was modern C. Not C++, not java, not C#, not F#. It was C. The extraordinary, unexpected, return of C. You could write a modern server in C. You could write a modern application in C. It was amazing. It's now victim of its success and might become an industry language. As I mentionned, the grammar being changed, it's literally a new language that's being born. Go++ is being born. Why would you terminate a language which in 12 years has become one of the top 5 choices on the server?
This is not a sensible choice. This is not the choice of the hackers. This is the industry putting its dirty paws on a great piece of technology.
At first I read this as "suitable for programmers who are 10x more productive than average ones". But they must be able to judge when/how to use generics.
Do you mean programming with 10x more code, or 10x more developers?
I hope we can see some good examples of generics being used in the standard library once 1.18 is released.
Then why are you programming in Go, instead of directly writing x86-64 machine code? Remember that even assembly is an abstraction...
Woah there. No, it is not "well known", nor is it correct. Over abstraction is very problematic (and very common), true. But under abstraction is also problematic. There is a sweet spot, and it's hard to find. But the correct answer is emphatically not "no abstraction".