296 points · by Danieru · 7y ago · 287 comments
To me seemed like C was such a tight, perfect little design.
Only thirty keywords, and simple consistent semantics.¹
When I first learned it, it was still pre ANSI, and you declared a function like this
int f(a)
char *a
{
}
The ANSI style function declaration was maybe the only innovation that came after that that significantly improved the language.
I remember in the late '80s knowing my compiler so well that I could tell you what the stack frame would look like pretty much anywhere in my code. It was awesome to have that level of familiarity.
Soon after that things started to get more complicated, and I did a lot of Java, and I never again felt as dialed in to those languages as the late 80s C that I started out with.
The K&R book is worth a read if anyone missed it. It's beautifully written. A far cry from the 'opinionated' copy that you often find on the Go website.
Personally, I don't think you can make similar claims about Go's design or the 'because I told you so' tone that surrounds it.
1: Yes, I know, undefined behaviour, but this is my post and this is how I feel about C.
Smalltalk is a tight design. So is Lisp. So is Forth. So is APL. C's design just feels like a pile of... stuff. Arrays are almost but not quite the same as pointers. You can pass functions but not return them. There's a random grab-bag of control flow keywords, too many operators with their own precedence rules, and too many keywords given over to a smorgasbord of different integer types with arbitrary rules for which expressions magically upconvert to other ones.
#include <stdio.h>
char *f(void) {
return "Yes, you can...";
}
char *(*g(void))(void) {
return f;
}
int main() {
puts(g()());
return 0;
}There's a big misunderstanding here. Arrays and pointers are entirely different things. An array is a chunk of elements that lie next to each other in memory. A pointer is just a pointer.
The only thing that C does that causes confusion is pointer decay. If you use an array in an expression context, other than the sizeof operator, that expression evaluates to a pointer to the first element of the array.
And while it's confusing the heck of many people who never learned it properly, it's very useful. For example, string literals are arrays, too! Would you prefer to write printf(&"Hello, World\n"[0])?
That's it, in a nutshell.
Funny, I got the same feeling from Smalltalk and Lisp.
I own both "Common Lisp: The Language" and "Smalltalk-80: The Language and its Implementation", and while there are many ways those languages could be described as 'tight' (tightly-coupled, perhaps), at no point can you look at the C language and say "This could be smaller" without significantly removing functionality. Ok, perhaps there are some things around array/pointer syntax, etc. but the room for removing things from the language is very small.
LISP and Smalltalk are both 'kitchen-sink' languages. As I understand it (i.e. Unless I misread something or skipped a page) for an implementation to be a proper spec-conforming instance of Smalltalk-80, a screen and graphics server is required. Indeed, Smalltalk-80 requires a very specific model of graphics display that is no longer appropriate for the time. Steele's Lisp, has a number of functions that one could strip out and nobody would care or notice very much.
On the other hand, all of the C that is there serves a purpose.
Perhaps the only thing in your list that does feel like a tight design in addition to C, is FORTH. But FORTH puts the burden for the programmer to remember what is on the stack at any given time. It has some beauty, indeed, but all of the abstractions seem inherently leaky. I haven't programmed in FORTH, however, so I can't really talk more about how that plays out in practice.
If the "There is nothing else to remove" does not resonate with you, then I think the perspective of the OP, and myself, and others, when we call C a "small"/"tight" language, is that essentially, C was born out of necessity to implement a system. Conversely, the 'batteries included' aspect of Smalltalk and Lisp more or less presume the existence of an operating system to run. It feels like the designers often did not know where to stop adding things.
Most of the library functions in C, can be implemented very trivially in raw C. Indeed, much of K&R is just reinventing the library 'from scratch', there is no need to pull out assembly, or any more assumptions about the machine other than "The C language exists". Whereas, a lot of the libraries of Smalltalk and Lisp seem bound to the machine. Not to harp on too much about the graphics subsystem of smalltalk, but you couldn't really talk about implementing it without knowing the specifics of the machine. And while much of Lisp originally could be implemented in itself, Common Lisp kind of turned that into a bit of a joke. Half the time when using it, it is easier and faster to reimplement something than find whether it exists.
Apologies if this is repetitive or does not make much sense.
To me, ANSI C is “tight” in the sense that it is made up of a small set of features, which can be used together to get a lot done. But the design of the features, as they relate to each other, can feel somewhat inelegant. Those different features aren’t unified by a Simple Big Idea in the way that they are in Lisp or Smalltalk.
Lisp and Smalltalk, then, have “tight” designs (everything is an s-expression/everything is an object) which result in minimal, consistent semantics. But they also have kitchen sink standard libraries that can be challenging to learn.
(Although to be fair, Smalltalk (and maybe Common Lisp to a lesser extent) was envisioned as effectively your whole OS, and arguably it is a “tighter” OS + dev environment than Unix + C...)
FWIW, I am learning Scheme because it seems to be “tight” in both senses.
Standard libraries are a different matter, but I'm not too impressed by C there either; it's not truly minimal, but it doesn't cover enough to let you write cross-platform code either. Threading is not part of the pre-99 language spec, and so you're completely reliant on the platform to specify how threads work with... everything. Networking isn't specified. GUI is still completely platform-dependent. The C library only seems like a baseline because of the dominance of unix and C (e.g. most platforms will support BSD-style sockets these days).
I'm actually most impressed by the Java standard library; it's not pretty, but 20+ years on you can still write useful cross-platform applications using only the Java 1.0 standard library. But really the right approach is what Rust and Haskell are doing: keep the actual standard library very small, but also distribute a "platform" that bundles together a useful baseline set of userspace libraries (that is, libraries that are just ordinary code written in the language).
Common Lisp is kind of a language and a library. Parts of the library would be optional. Some standardization efforts (EuLisp, R6RS, ...) tried to defined a Lisp like-language in layers/modules/libs later on.
That said, given my comfort level and tendency to be more explicit rather than tricky, my C coding ends up surprising me a week or so later when I go back and realize "even at 2am" I did the right thing.
It's also a fun language to mess with junior programmers with.
the piles of stuff that C contains are the stuff of 20th century von Neumann architectures, the stuff that defines the undefined behaviors, and that's what has made C indispensible.
I'm not saying C's perfect, but you can't swap it out without replacing what it did and does.
Except that clearly history showed that it wasn't enough, and we ended up with about 50 millions (and counting) different meaning for "static" for instance. I like C but its simplicity is almost by accident more than by design. It's pretty far from "perfect" in my book.
There are so many weird features about the language that can bite you ass for no good reason. Why don't switch() break by default since it's what you want it to do the overwhelming majority of time (answer: if you generate the corresponding assembly jump table by hand "fall through" is the easiest and simplest case, so they probably kept it that way).
Why do we have this weird incestuous relationship between pointers and arrays? It might seem elegant at first (an array is a pointer to the first element or something like that) but actually it breaks down all over the place and can create some nasty unexpected behavior.
Why do we need both . and -> ? The compiler is always able to know which one makes sense from the type of the variable anyway.
String handling is a nightmare due to the choice of using NUL-terminated strings and string.h being so barebones that you could reimplement most of it under an hour.
Some of the operator precedences make little sense.
Writing hygienic macros is an art more than a science which usually requires compiler extensions for anything non-trivial (lest you end up with a macro that evaluates its parameters more than once).
Aliasing was very poorly handled in earlier standards and they attempted to correct that in more modern revisions while still striving to let old code build correctly and run fast. So you have some weird rules like "char can alias with everything" for instance. Good luck explaining why that makes sense to a newbie without going through 30+ years of history.
The comma operator.
Undefined function parameter evaluation order.
I suspect that with modern PL theory concepts you could make a language roughly the size of C with much better ergonomics. I'm also sure that nobody would use it.
If this is true, then that makes perfect sense. C was attempting to look after its target market: assembly programmers.
I've often wondered this myself. The best I can come up with is that the underlying code generation includes an additional dereferencing step with ->, so having both . and -> makes the compiler a little more transparent.
Of course, in C++ you really need both because overloading -> is nice for e.g. objects that want to look like pointers.
> Why do we need both . and -> ? The compiler is always able to know which one makes sense from the type of the variable anyway.
You're contradicting yourself in a way.
Maybe K & R thought: "Why can't arrays decay to pointers? The compiler is always able to know which one makes sense from context anyway."
I agree with the your opinion about arrays/pointers, but disagree about ./->. A programmer reading the code might confuse a pointer for a non-pointer if you conflate . and ->
Or Zig (which is less superficially C-like on the surface, but is going for the same simplicity and low-level-ness).
The reason is that Dennis Ritchie wrote a submission to the committee¹ that described the ‘noalias’ proposal as “a license for the compiler to undertake aggressive optimizations that are completely legal by the committee's rules, but make hash of apparently safe programs”, and, that “[i]t negates every brave promise X3J11 ever made about codifying existing practices, preserving the existing body of code, and keeping (dare I say it?) ‘the spirit of C.’”
Those comments describe what ‘undefined behaviour’ turned in to. The only reason dmr and others didn't make the same objections to it is that nobody realized at the time what the committee wording implied.
¹ available here: https://www.lysator.liu.se/c/dmr-on-noalias.html
So books of that day where written so you could learn a lot just from reading the book and thinking seriously about the examples, and working out the exercises in your head or on paper
It helped if every couple of days or so you could get some computer time and try out the things you learned, but it wasn't actually necessary. In the case of K&R, you could go through the whole book without touching a computer, and then one or two sessions afterwards trying things out could be enough to correct your misunderstandings.
I wish more books were like that today. Nowadays, they assume you are a computer all the while you are reading the book, and often depend on that when writing the text.
"const" as well (back ported from C++ ?). And being able to declare variables anywhere (instead of just at the beginning of a block)
Also, ironically, I feel like C presents an excellent case for an evolved language, not a designed language. Its very name is derived from BCPL, as are many of the semantics and notation.
It many ways Go feels like an updated C. It retains most of the basic abilities of C, while cleaning up some things (headers, etc), having more basic libraries included, and choosing some defaults around things like out-of-bounds array access that are probably more appropriate for the majority of most programs (outside of particular hot loops, etc) in an era where software is often connected to the network and security is a bigger concern.
[1] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=30475, http://blog.llvm.org/2011/05/what-every-c-programmer-should-...
Undefined behavior is a great way to help the language help you; for instance, most loops look like infinite loops without it. All you need to do is test with ubsan to see if you're dynamically undefined anywhere.
https://www.digitalmars.com/articles/b44.html
A mistake that C++ missed an opportunity to fix.
But when the article implies that null terminated strings and the problems associated with them are caused by arrays decaying to pointers, I get more skeptical.
I mean it's not as if arrays in C are bounds checked anyway, so how would that have helped implement strings any better?
I guess you could have bounds checked them in the stdlib code, but you certainly wouldn't have gotten it for free just by knowing the array dimensions.
Perhaps you were referring to C++, or some newer C dialect?
What I mean is, the K&R C had very few (if any) abstractions, other than those defined by preprocessor.
Like, you could look a the C code and pretty much "see" what the assembly code would look like after compiler did its work.
I've never used it for work or open source or anything "real".
Agreed. I read the whole thing in a weekend and had a pretty good idea about pointers and stuff afterwards. I feel a lot of people have trouble with pointers didn't read it.
* ZX Spectrum BASIC
* Assembly language (Z80)
* FORTH
* C
* ..
Learning C when I already knew assembly language made it obvious what pointers were. I suspect a programmer these days might start with javascript then jump to C and be a little mystified.
What impresses me is reading Burroughs manuals, or the manuals, books and research papers from Xerox PARC and IBM in the 70's.
That being said, Go isn't perfect by any stretch. Sometimes panic ins Go routines can be very hard to trace. The transition to Go modules is challenging for larger projects with versions beyond 1.x (when I started it was Glide, then dep, now go mod, which has been a bit frustrating). However, I wouldn't go back to Java, C#, PHP, or NodeJS if I had the choice.
My go to in the server space is Go and Elixir. I don't feel a desire or need for anything else, but again, that's me. You know your use case better than a stranger on the internet :)
But even more significant is that the Go authors cannot seem to grasp the importance of pre-existing conventions. Almost every language I've used in the past decade allows and encourages the variable, Class, CONSTANT convention.
It reminds me of people who want everyone to use CE and BCE instead of AD and BC, ignoring the inertia and relevance of the latter and almost seeming like we live in a vacuum where fresh ideas have as equal weight as old ones, and history doesn't matter at all.
I don't know how to explain this better, but this is basically the core reason I don't like Go, above and beyond any specific features or lack of features.
I once heard Go described as "what if we took the good ideas of C and started from scratch?" But it feels like they take that very literally, as if they were saying, "what if it was actually 1970 right now, and we didn't have C, and the next 49 years never happened?"
(This is a separate reply than my other one because someone already upvoted that.)
I realize that not everyone's preferred editor may support every language yet, but still I think the solution to this problem is probably just having the language designers provide libraries that editors can use for these refactoring features, instead of through specific capitalization conventions.
What "pre-existing conventions" do you see in the Go code that you've had to refactor? The fact that conventions from Java or C++ aren't the same simply reinforces the fact that Go is a different language, and that's A Good Thing.
I could see using it for CLIs and various Unix scripting, but I've been doing that with Ruby, for the most part. I also considered learning Go for creating some native binaries for a few critical paths, but Rust seems like the best choice for that. A NIF that crashes is one of the few things that will take down the Erlang VM, so Rust's strong safety guarantees (might) make it worth the steep learning curve.
My question was how the poster was using Go with Elixir. Since they have a big overlap in what they're commonly used for and since NIFs (Natively Invoked Functions) on the BEAM really need to be fail-safe, it's not as clear as how to use these two together as how one would use C in the same stack with Python, for example.
From a lot of what I've seen, that is a useful description.
If you come to Java with a blank slate, and try using it with simplicity in mind. There's not much wrong with it. But once people add design patterns, layers of layers, reflection, annotations. Etc. You get a monster. And somehow, the enterprise world seems to always create those.
Not exactly a novel take: https://dirtsimple.org/2004/12/python-is-not-java.html
- Compared to Java: Ecosystem is way over-engineered. You might get along just fine without writing a bunch of boilerplate and factories and XML configs, but sooner or later you're probably going to pull in some dependency that does and have to deal with a bunch of clunky APIs and other annoyances.
- Python: Possibly the only language that's even worse at dependency management than Go. Installs packages globally. The solution is to create a "virtual environment" which is code for hacking up your PATH.
- Node: I dislike the quirks of Javascript like remembering the difference between == and ===, undefined vs null, etc. I haven't used Typescript which may solve some of those language issues. I also dislike dealing with promises/callbacks for so many operations.
I like Go because:
- I can compile to a single statically-linked binary and cross-compile for other platforms
- I can choose to either vendor dependencies or use go-dep to create a dependency lockfile. I can have multiple GOPATHs with minimal magic.
- The "go" CLI handles pretty much everything I need without an explicit config file like pom.xml or package.json.
- The language lacks features. There is no magic. Way more so than even Python, there is one obvious way to do things and there's even an official style guide, so it's easy to jump into someone else's code and understand exactly what's going on immediately. After working with Scala professionally for a few years, I firmly believe this to be a feature, not a flaw.
- The standard library is incredibly comprehensive. It's completely possible to write a web service without importing a single external dependency. There has been a lot of thought put into library APIs for things like byte Readers/Writers and HTTP handlers, to the point that external libraries still usually stick to these standard interfaces. Contrast that with a language like Python where urllib sucks so everyone uses requests.
> == vs ===
Just never use ==, and you're done. This is pretty much a defacto standard. It essentially has no legitimate usecase that couldn't be expressed more explicitly with at most 1 extra line, and should just be ignored.
> undefined vs null
I've only very occasionally run into this being an issue. Standard seems to be using the falsey nature of both undefined and null to check for them, !x rather than x === null for example, so that it doesn't really come up much in practice, but anyway...
> TypeScript may solve some of these issues
Yes, it solves both the above :-)
> Dislike dealing with promises / callbacks
Firstly callbacks are hardly seen anywhere any more. And if they are, certainly no more than one level deep, and that's even assuming you don't just promisify the callback function anyway, which is trivial to do.
For Promises - async/await makes dealing with them syntactically much nicer in node. It's pretty much just like synchronous code to read, and in behaviour.
As far as Python, same kind of reasons. Single binary makes deployments easy, static analysis and built in tooling makes life easier, and I just find it more enjoyable, which is completely subjective.
1. Java - did not want to adopt the entire ecosystem. This is very much wanted a banana and got the whole jungle with a gorilla type of story.
2. Python - dynamic. Don't want that. Go's minimal typing is perfect. It's easy to deploy (binaries). It's fast. It can scale well. It's opinionated (love this).
Python and Java both encourage and allow developers to flex creative solutions that are hard to maintain long-term. Sure, seniority helps with that, and being part of a good team; however using Go, you just run into that less due to the conciseness of the language and strong idioms.
I work on Golang stuff at work where we made the switch after the troubles associated with refactoring Python. Recently though, I 'typed' a personal project of mine that was fairly large, and it's become a pleasure to work on.
IDE integrations of mypy warn you as soon as type errors occur. The fact that the type annotations are first-class features of the language and not embedded in comments also makes it great. The compromise of type-safety at the boundaries where you interface with 3rd party APIs that don't provide type annotations (the major ones do) does not get in the way too often contrary to what I expected.
mypy makes Python a pleasure to work with again.
"If your program is small and can mostly be described by what it does... then Go is fine. If it’s large, if it has non-trivial data structures... or if it will be dealing with a lot of data from the outside, then the type system will fight you for no benefit and you’re better off using a different static language (where the type system helps) or a dynamic language (where it doesn’t get in your way)."
That's a much better way to express my sense after almost a year of working with it that I'd ended up with a Pascal-like subset of Java with most of the liabilities of the former. And I wanted to like it going in ("hey, some people love it, and it's more or less Gosling's statement about Java w/o classes come to life!").
Stopping compilation with an error for every unused import & variable is particularly annoying, so much so that I've patched the go compiler to treat them as warnings instead [1].
Ultimately, I think the problem boils down to a language that outgrew its original design, and hasn't evolved elegantly (yet).
Also regarding warnings/errors: time-travelling back into the 90s it was normal that C/C++ code - also in Open Source Projects - was full of warnings and often not portable across compiler/library versions. That was a major pain, I remember myself experimenting a lot with compiler flags (-Weffc++, -strict etc.) for my own code that also prevented stepping into common pitfalls.
Except that it only happens in C and C++.
Why? Because C and C++ were designed to have sharp edges for you to cut yourself. The default behaviors are absolutely bizarre and stupid, and the breadth of things that are undefined behavior guarantees that any given program is non-conformant. Warnings and -Werr and linters were the only possible ways to keep any semblance of sanity and code quality.
But we're not talking about those dangerous languages and their sordid history. We're talking about the here and now and modern languages, where an unused import NEVER causes bugs, and where unused values aren't flagged as errors in any other language for good reason: we debug code far more often than we write it, and slowing the debug process for the sake of cleanliness is stupid.
And it still astonishes me how unused values are treated as errors in a language that happily allows variable shadowing that is literally one colon away (= vs :=), and doesn't allow file-level variable and function isolation. Those are FAR more dangerous and bug inducing.
Speaking of myself, in various programming languages both ancient and modern I've run into the situation where debugging is difficult because of hard to read code. Code written by others (or written by myself 6+ months ago) is always more difficult to read. Even more so when there are unused artefacts ("dead code").
So often it happens that people have to work under a lot of time pressure and write 300 lines for something that can be solved in 30 lines in the same language. It doesn't matter so much usually but when there is a difficult bug, sometimes the only way to solve it is to thoroughly understand the code. For me it's often easiest to just remove dead code/compactify existing code so there is less code I have to reason about.
Probably a lot of Go's design is about simplicity, its spec can be read in 1-2 afternoons if you're already familiar with the language.
Everything being an error makes this worse not better; if -Wdeprecated turns into an error you're just not going to be able to fix everything in someone else's code. Unused code being an error is easy to fix, but it's so disrespectful. I shouldn't get compile errors as I'm editing when I haven't done anything wrong.
It's been a long while since I last touched Golang, but I recall the process of learning it.
My coworker and I were tasked with creating an interface for our employer (a cloud service provider) to allow Rancher (or clients of Rancher - I forget) to use our backend system (which was built out of a combination of PHP, Java, and Bash - among other parts) to provision servers.
Neither my coworker or I had ever touched Go; we were PHP developers. But Rancher used it, had examples, and we set out to learn it (while we were employed as PHP developers, we both had extensive prior experience with a number of other languages).
It took about a week until we were comfortable enough to begin our implementation, and about a month later we had a working library written in Go that we understood and had documented well, with tests.
But the process: Exactly like you noted! We railed, we gritted our teeth! We shook our fists at heaven and loudly proclaimed "WHY?!"
Because we were so used to leaving things lying about in PHP; for experimentation, debugging, and other reasons. But Go wouldn't let us - no-siree-bob! - you had to make it just so before it would successfully compile, and we tore our hair out over it. Day after day, week after week...and then:
Something changed. We understood. We realized why the designers of Go did what they did, and we also started to wish fervently that PHP could be the same way. We also noticed that by these changes, we no longer needed to leave this "cruft" around, this "dead code" that could possibly cause us to trip up, or wonder if it was needed later, or whatever. Yes, it made development more difficult - but we came to recognise that it helped greatly to prevent errors, or future problems, and kept things very maintainable.
But like I said - I haven't used Go in years since that time; there hasn't been a call or need for it, but it is a language that I keep in my "back pocket" just in case I ever need it. Maybe things have changed a lot since then, or maybe they haven't. Regardless, I learned from that experience that sometimes you have to power and struggle through things before the revelation appears. I got to experience a fairly unique language, and I feel that I'm better as a developer for it.
In the end it's just about the variables anyway, most IDEs will remove unused libraries automatically.
Like having an annoying wife (erm, spouse) constantly tell you you've wrong all the time. In the end, some if not all will understand and adapt their behavior as complaining is of no further use.
I think the worst part of that decision is I've never seen a bug arise from unused imports and variables (even in languages with ubiquitous importing side-effects like Python, imports and import ordering can cause issues but usually you need the import anyway, you can't just nuke it).
Meanwhile variable shadowing / overwriting or unused return values which do cause issues are perfectly fine by the compiler.
To me this is more of an issue with not understanding some of the conventions the language pushes you towards. An example of this common stylistic mistake is when some repos will have a `lib` package with a large number of utility functions spread across different files. It runs into the author's issue of function and constant collisions. The solution is to group together utility functions into many small packages, which has the added benefit of changing the code at the call site from something like this:
lib.NewUUID()
To something terse like this: uuid.New()
I've found that Go has lots of these sorts of nudges — dependency cycles generating a compiler error, for example — where the language enforces good style and organization.However, if the Go compiler is going to enforce these rules, maybe it could be more helpful by suggesting the design tweaks that would help to avoid them, rather than forcing developers new to Golang to go through a kind of trial and error process.
> Structs do not explicitly declare which interfaces they implement. This is done implicitly by matching the method signatures. This design makes a fundamental error: It assumes that if two methods have the same signature, then they have the same contract.
Isn't this just duck typing? Don't other languages renowned for their type systems do this?
> There’s no ternary (?:) operator. Every C-like language has had this, and I miss it every day that I program in Go. The language is removing functional idioms right when everyone is agreeing that these are useful.
Expressive if/else is much more readable. Of course if Go doesn't have that, removing the ternary operator is a bad call.
> The tried and true approach of providing a compare method works great and has none of these drawbacks.
Hmm... except in anonymous cases. This author clearly has some Java stockholm syndrome.
> The append() function modifies the array in-place when it can, and only returns a different array if it has no place left.
That's horrifying.
Yes
> Don't other languages renowned for their type systems do this?
No. In languages with good type systems, nominal types are very valuable. E.g. "known-immutable list" and "read-only view onto a mutable list" are very different types, but offer the same set of methods.
It's "structural subtyping", which is the type-safe equivalent of duck typing. It's a feature that allows implementations to exist without needing to know exactly every interface they implement. TFA's concern is purely theoretical.
> That's horrifying.
append() doesn't operate on arrays, it operates on slices. Arrays are fixed-length, contiguous blocks of memory that can't be appended to. Slices are backed by arrays, and if you append to a slice whose backing array is full, it will "grow" by allocating a bigger array elsewhere and copying the original data into it. This is a pretty standard data structure in most languages.
Yes, vectors are common, but they don't typically require compiler modifications to avoid mis-using them. In this case I'd make it super clear whether the method mutates the existing value or returns a new one, and "possibly both" seems like the worst of both worlds. If this behavior is preferred, it seems like `append` should take a handle to a slice pointer, possibly to a slice rooted in the stack, and write to it if replacing the underlying slice.
https://play.golang.org/p/qWCnF7d7Fl9
This is unexpected behavior at best.
Vectors are standard data structures.
Append possibly mutating in place and possibly return a new vector instead, not so much.
That's exactly what Go does.
Not to mention the ability to share a backing array between two "vectors" and to append to both. That's a Go innovation right there.
It's been pointed out in the comment right below this, but it is a bug if you do this. If the backing array has any free capacity the results will be very different from what you expect.
If you go with most languages definition of "slice", that would be pretty horrible just by itself.
But, as you said, Go's definition is different (what is also bad, just not much):
> Slices are backed by arrays, and if you append to a slice whose backing array is full, it will "grow" by allocating a bigger array elsewhere and copying the original data into it
What would be pretty much like Java's ArrayList, or Python's list if it was designed on a sane way. So, just the name would be non-standard... But the container actually migrates when it is reallocated! That's a broken design in any language.
Most languages don't have a definition of "slice" at all.
> What would be pretty much like Java's ArrayList, or Python's list if it was designed on a sane way. So, just the name would be non-standard... But the container actually migrates when it is reallocated! That's a broken design in any language.
It's not broken, it's just fast and simple. But yes, it does require you to know that Go's slices are not exactly Python's lists (which do gratuitous copies). Java's implementation does an insert on the original list (both surprising and an unnecessary copy).
If you say so. I know I should go read the docs more carefully, but this whole slice thing is confusing to me, and often yields surprises like this.
I'm not a big fan of how this was implemented.
v := a; if t { v = b }
Sadly, this doesn't work well if a is a function call :-(go fmt may not be anyone's favorite code style, but having go fmt is so much better than dealing with everyone else's favorite (incompatible!) styles.
It has no switches to disable features.
It destroys many nice single-line constructs, e.g.
if err != nil { return err }
Much of my code would be painful to read without that one.On the bright side, it artificially inflates your line count, so you appear more productive!
Is it more powerful in some way than the auto-formatters that exist for nearly every other language?
Edit: I didn't mean this as an insult, I meant it as a genuine question. I don't know much about the Go ecosystem, and I meant to find out what Go's killer feature is in 2019, when other languages now have strong and elegant concurrency, C-like performance with higher-level syntax and without manual memory management, etc.
Of course, this is not as good for having fun programming, unless the programmer feels having written something is more fun than writing it.
Fast compilation speed, easy integration with C, and the "one large static binary" are probably my favourite features, although I do wish those binary sizes weren't quite so large...
I do not like Go the language but I can begrudgingly admire the ecosystem
I am so grateful for the Go creators for having made it as it is. What worries me is the recent changes: modules (never had a problem with GOPATH) and Go 2 proposals. I hope they are able to keep their vision as it started.
I actually fall into the opposite camp. I never felt comfortable with GOPATH, but found modules extremely natural, perhaps because it's somewhat analogous to how NPM works: go mod init -> nom init; go get -> nom install...
Same as Rust replaced C and C++.
That anyone would want to write C/C++ or Java today is absurd, except if they're old.
Maybe time will tell, but I'd lay money that there will be a lot of people still working on C, C++ and Java codebases in fifty years, just like there is a boatload of COBOL and even MUMPS software still out there in the wild today.
What happened over time was that we developed a way of using Java that was less painful. And it turned out that the bones of Java are actually quite good. If you strip away a lot of the cruft people glom onto their code in the belief that it saves them time, adopt sensible ideas from how other languages want you to think, and keep things very minimal and consistent, Java can actually be quite pleasant.
But this requires you to have someone in your company that can teach people. Often peope with many years of experience who will initially insist on not changing their ways.
(The main reason I don't like Java isn't down to the language itself. It is because I don't trust Oracle. It took me nearly a decade to ditch Java as my primary language, but Go provided me with a viable option. Sure, it'll take some time still to reach the level I was at in Java, but after about 3 years, things still look good)
This might not be the most efficient way to walk, but once you've done it for a while it starts to feel natural.
Picking a language involves compromise.
I think what I perhaps reacted to were the somewhat superficial nature of the blogger's complaints. Especially when claiming to have done non-trivial projects in Go. Perhaps as a programmer, but it doesn't sound like someone who has lead development and had to make hard decisions.
Non-trivial projects usually give you plenty of other things to worry about. For instance how good the language is for collaboration, how easy it is to model things, how clear is the code, how does it make use of the machine resources, will the language still have a following 10 years from now, what does the tooling look like, what quality are the open source contributions, is the standard library usable, do the third party libraries cover enough of what you need?
And then there are the developers. You need to be able to recruit developers beyond your circle of friends. You want that pool to be as big as possible. This is why I avoid languages that have too little mainstream appeal. It doesn't help me much if I can hire some Common Lisp guru to build a lovely piece of software if I can't find anyone to maintain it once he or she leaves.
Being the one to decide what language to use for a project is a thankless job because you will always disappoint someone. Not everyone will or can take in the larger perspective. As a manager I seriously do not want to hire developers that always want to program in some other language, often one with a small following. Or who want to change languages every 2 years. Because if they can't learn to live with one of a selection of mainstream languages that are "80% okay", why would I think they are any better at dealing with difficulties in other languages? I expect good programmers to adapt practices - to make languages work for them. To be professionals.
When we switched from Java to Go in my department it was a team decision. As a manager I let my team decide what to use, HOWEVER, I made it clear that everyone will make an effort to learn whatever is chosen and I don't want any whining or excuses. If they found Go to be the wrong thing, fine, we have Java which is the devil we know to fall back on. But only after everyone has made a real effort.
That was 3 years ago. We now have somewhere in the neighborhood of 100kLOC running in AWS and it has been astonishingly productive. Sure there has been _some_ whining about small details, but on the whole adopting Go was surprisingly fast and surprisingly pain free.
I understand why people might dislike a particular language and that's cool. That's why there are many languages and we have the ability to choice what works best for us.
The capitalisation is maybe the most annoying for me, I think it was designed with an IDE in mind (which would be able to automatic update all references), but I still find it a flawed design to have to touch potentially a lot of files, many places to change something from private to not private.
The problem with err has also bit me a few times. I don't like exceptions very much, but a solution like he suggests where a variable can only be ignore explicitly would solve it.
Go is not perfect, but for me there is nothing else better for microservices that I have come across.
If you don't have an IDE, you can start by making all functions and methods private. When you know you need it public, wrap the private function with the public one:
func myF(ana int) { /*do something */ }
func MyF(ana int) { myF(ana) }
The same trick is often used for adding extra parameters to a function, except that the function body must be moved: func myG(a int) { myG2(a, 7) }
func myG2(a, b int) { /*do something*/ }
Adding publicness to a function is like adding an extra parameter to it.Like Rust :)
Golint can enforce the "don't ignore errors" rule. I think it comes that way out of the box?
Seq(1, 2) map _ + 100
They are getting rid of it: https://contributors.scala-lang.org/t/lets-drop-postfix-oper...Unit functions were a thing, just write:
def A() { ... }
This is inalid since 2.13. You have to specify its a unit: def A(): Unit = { ... }
Most of the ideas in scala were to remove boilerplate, but they backfired. The top example had an issue, were the following conversion used to be made: z op ()
// would equal to
z.op()
// instead of (fixed in 2.13)
z.op(())
Arrows are used for creating key-value pairs and such. Someone added nice Unicode equivalents for them. Those got deprecated in 2.13 Deprecated: ⇒, →, ←
Use instead: =>, ->, <-
https://github.com/scala/scala/releases/tag/v2.13.0Indeed, i've been impressed by the Scala team's recent willingness to remove complex features generally. I didn't see that coming.
The first one is unreadable. If I saw that in a pull request at work, I would ask the author to change it. (But I wouldn't have to; the people I work with know better.)
For the second, it's confusing to have two different ways to write the same thing; arguably you should always be writing type ascriptions for function return types (even though scalac doesn't require them) both for readability and avoiding bugs.
For the third, argument list adaptation is a great way to write bugs by accident and not notice. Good riddance.
The fourth is really a style thing, and a pretty weak one at that. I don't want random untypeable unicode characters in my code when ones I can type will do.
It's an objective fact they removed features in Scala (I think that's a good thing). But dismissing the pointed issues as non-issues without explanation is what rubbed me the wrong way.
Overall, I'm a fan of losing a few helpful abstractions in order to get rid of all the bad ones, whether in the language itself or in it's ecosystem. And Go delivers on that.
I'm really surprised people like Rob Pike and Ken Thompson would design a language where the visibility of an identifier depends on the case of its identifier.
I would not be surprised if specifically the Google C++ style guide influenced this decision.
the language comes with a rewriting tool that rewrites arbitrary expressions.
gofmt -w -r 'thing -> Thing' *.go
* Changing the visibility of a variable requires changing its name, everywhere it's used.
* It also cuts contrary to some very long-standing traditions, like using all caps for global constant names, using title case for class names, and starting with lower case for most everything else.
serializeType := model.SerializeNonArchivedOnly
if showArchived {
serializeType = model.SerializeAll
}Not to mention you are mutating an already assigned variable. You run in to problems when you want to know the type of serializeType and you look at the first assignment but don't see that there is a second one.
Go is statically typed, so the type of serializeType doesn't change, only the value.
For 2, I hate this example. Code that returns or takes booleans that requires reading a comment to understand the value is super error-prone to use. Don't write textually ambiguous interfaces in any language. I just haven't seen this particularly be a problem.
#3 Re: checking errors, we wrote a trivial go vet plugin in house that checks for that.
sort.Slice is probably new since this was written and is way better than sort.Interface if you're sorting a slice.
Better vendoring and generics are finally acknowledged to be issues and solutions are coming. Hooray.
You don't use Go for the language design, you use it for the tooling.
I always tell people, "I love everything about Go except for the language."
See Java[1], C#[2]. Both have good compilation speeds (which don't really matter when you have incremental compilation anyway), as well strictly superior debuggers.
[1] https://quarkus.io/ [2] https://docs.microsoft.com/en-us/dotnet/framework/tools/ngen...
https://www.teamten.com/lawrence/writings/java-for-everythin...
It got lots of attention in a couple of months since the public release, and I often hear people say that they feel like this is "Go done right".
It'll be open sourced by June 20.
[0]: https://vlang.io
I don't think it's possible to modify structs on the fly.
Maybe it is, I need to think about it/do research.
EDIT: Assuming inlining and call-by-value struct is a possibility.
I'm really hopping that Golang finds a way to either not add generics, or add them in contrained ways. Your example code for generics are very hard to read for example.
Rust somehow tackles that with associated types, but since generics are still allowed it's not great imo.
Why do you find them unreadable, because of the angle brackets?
I've considered using
struct Repo ⟨T⟩ {
db DB
}
Instead of struct Repo <T> {
db DB
}
The conversion would be done automatically by vfmt.The ultimate test is to read someone else's code and try to figure out what is the actual struct being used in place. You will see that you often have to jump through many many files in order to get a sense of what is actually used in place. This problem becomes even harder when people start nesting generics.
Take a look at associated types in Rust. I think it is a better way to do generics because it forces you to specify the type early. It also prevents nested types that are hard to read like <T<A, Cat<B>>> (and this is nothing)
Some of the problems are really annoying and artificial such as "declared and not used/unused imports" trying to push golang opinion on code quality
Go apparently does it that way to make "defer" work.[1]
Would you consider it a good thing to be forced to do?
Moreover, there are functions for which "not ignoring" the return value isn't the same as "checking it" (e.g malloc, fopen, etc.).
(CppCon about error handling: https://www.youtube.com/watch?v=GC4cp4U2f2E )
> Idiomatic Go uses shorter names like u, but I stopped using one-letter variables 35 years ago when I left TRS-80 Basic behind.
Ignorant snobbery. Skip.
The actual problems like versioning, error handling and generics (may be) are being worked on.
I have seen many new learners find it hard to learn what packages mean, and how about teaching them private, public, static, ...
- faster time to market
- good runtime performance
Looks good to me.