415 points · by Manishearth · 11y ago · 213 comments
Anyway, just like the author I found myself fighting the forced directory structure at first, but it's something I started to like about Go: Go doesn't come with a complicated package management. All packages lie in a directory and you can edit everything with normal shell commands. This keeps things refreshingly simple.
Go's lack of generics and its incapacity for functional programming are mostly unrelated.
As an example in favor of their coupling it is very hard to write generalized functions for list operations without generics (without duplicating code). It is especially hard if you want to maintain type safety and don't resort to type erasure (interface{}).
What is the connection? There are tons of functional languages (Tulip, Racket, some Lisps) that are untyped or optionally typed.
Strong types are awesome, but you don't need them for FP. Go isn't good at powerful typing or functional programming.
HKTs are very useful for e.g. typeclasses (used for Monad, Functor, etc. definitions) but you don't need them. Strictly speaking, you don't even need types at all (even though they're great).
> Too many Go reviews turn out to be: Watch me trying to use Go as a functional programming language and fail miserably because it lacks generics.
You replied:
> Which part of his review was about functional programming in particular?
I think you totally missed zuzun's point. The point was not that this review was about functional programming, the point was that this review was not about functional programming.
He says "Go seems to advocate runtime over compile time checking." I think it's less that folks prefer run-time checks on principle than that they simply don't yet have in hand great ways to strengthen compile-time safety while meeting their other goals (meeting backcompat promises, not complicating spec/impl too much, other work like shorter GC pauses or new platform support). As an example of a team member not being a fan of all the runtime checks, bradfitz complains about the occasional gross interface{} here: http://talks.golang.org/2014/gocon-tokyo.slide#50 . And there is active work from the team and community on static checking, though most of that right now is in the form of heuristic checks in external tools, e.g., go vet and errcheck.
All in I love this--I tire a bit of posts that are like "I wrote a toy program [or not even that]; here's Why Everyone Else Is Wrong" (because anyone could give an opinion that informed given a day or two, and hot takes are getting old). But it's cool to see someone who, by virtue of working on Rust (and seeing it evolve) has unusual perspective on tradeoffs and seems to have written, you know, pretty thoughtfully and maturely about them.
> I think it's less that folks prefer run-time checks on principle than that they simply don't yet have in hand great ways to strengthen compile-time safety while meeting their other goals
Agreed, that sentence was a bit unclear from me. I did mean that they're okay with losing compile time safety over other benefits.
> All in I love this--I tire a bit of posts that are like "I wrote a toy program [or not even that]; here's Why Everyone Else Is Wrong" (because anyone could give an opinion that informed given a day or two, and hot takes are getting old). But it's cool to see someone who, by virtue of working on Rust (and seeing it evolve) has unusual perspective on tradeoffs and seems to have written, you know, pretty thoughtfully and maturely about them.
Aww, thanks :D
For more detailed information on the garbage collector improvements and roadmap for 1.5 and beyond, this document is the Roadmap and discusses improvements being made including a maximum of 10 ms STW out of every 50 ms. https://docs.google.com/document/d/16Y4IsnNRCN43Mx0NZc5YXZLo...
edit: fixed incorrect link
You should use locks for thread safety though.
That being said from a Rust background I like to be able to know what's going on at the lower level and Go makes that harder, but that's not a major issue whilst programming.
[1]Or internalize the borrow checker, which is something which eventually, automatically happens to all Rust programmers AFAICT. It actually spills out into other programming languages too so you get a nice involuntary mental tool to ensure safety in C++ :)
It's often possible to avoid sharing by passing discrete data around via channels. As a general rule, if it only has one owner, it's thread safe.
There's a Go idiom for that. If you have
type Doer interface {
Do()
}
and a type thing struct {
}
and you want to make sure that `thing`s implement `Doer`, just add this line: var _ Doer = thing{}
_ is a special value that can be redefined at will, so the pattern can be used as many times as needed. From there, the meaning should be straightforward: _ is a `thing` that implements `Doer`, so the compiler will check it. You get to keep implicit interfaces, that you can make explicit as you need.Apart from that, this post is really great; as someone "used" to Go and not at all to Rust this kind of impressions is always enlightening.
Then make a Draw() method on the single object default to what you expect. The simple inline explanation is:
type SingleObject struct {
Cowboy
Shape
}
Access is as follows to be unambiguous: Woody.Cowboy.Draw()
Woody.Shape.Draw()They all are the same interface and can be passed into each other's methods, leading to a logical error.
Yes, sometimes this isn't an option when you want to satisfy the interface for two different libraries, but I've not seen this occur very often. More likely you're in control of one of the interfaces; so rename your method to be more descriptive.
This is assumed in the description of the problem. Go has no solution for it. (Java doesn't either, but this is one of the things that C# got right over Java; it's unfortunate that Go has the same issue.)
https://play.golang.org/p/t0gjJHjU7y
Edit: another variation on the same idea: https://play.golang.org/p/FqSFpMKQuv
There is a paragraph in the faq (https://golang.org/doc/faq#guarantee_satisfies_interface) and one in "Effective Go" (https://golang.org/doc/effective_go.html#blank_implements), but I couldn't find much more than that.
While the capitalization of identifiers may be surprising, in practice it is one of the best features of go in my experience because no additional context is needed to know whether an identifier is exported. In rust, as far as I can tell, it is not possible without referring to the declaration.
As far as globally changing whether an identifier is exported, it is easy with the gorename tool, no search and replace necessary. Gorename also updates any references to the identifier in other packages in $GOPATH. https://godoc.org/golang.org/x/tools/cmd/gorename
Isn't this the same as the argument for Hungarian Notation? And isn't it a bit of a slippery slope? Why not add an 'i' for integers, so that no additional context is needed to know whether a variable is an integer. Etc.
There is a lot of information about a particular identifier that it would be nice to know at any given time, and in my opinion it's arbitrary to pick just one and make it a language rule. A much better solution is for to use IDEs or text editor plugins to visually show (using color, formatting, bits of UI) that information in a user-configurable and context-dependent way.
"Simonyi’s original concept for Hungarian notation was called, inside Microsoft, Apps Hungarian, because it was used in the Applications Division, to wit, Word and Excel. In Excel’s source code you see a lot of rw and col and when you see those you know that they refer to rows and columns. Yep, they’re both integers, but it never makes sense to assign between them. In Word, I'm told, you see a lot of xl and xw, where xl means “horizontal coordinates relative to the layout” and xw means “horizontal coordinates relative to the window.” Both ints. Not interchangeable. In both apps you see a lot of cb meaning “count of bytes.” Yep, it’s an int again, but you know so much more about it just by looking at the variable name. It’s a count of bytes: a buffer size. And if you see xl = cb, well, blow the Bad Code Whistle, that is obviously wrong code, because even though xl and cb are both integers, it’s completely crazy to set a horizontal offset in pixels to a count of bytes."
It's actually a practice I now use myself in certain contexts.
[0]: https://blog.mozilla.org/research/2014/06/23/static-checking...
Being able to declare that a variable is in radians, for example. (Bonus points if it can auto-convert.)
In Hungarian Notation, the type is enforced by a declaration, but it's documented by the prefix.
In go, the enforcement and documentation are one and the same.
>> bool iMyInt;
It's obviously wrong, but the compiler will happily compile it. When you declare the following in go:
>> type NotExported struct {}
You still know it's exported, no matter what BS the programmer writes.
> The other day I had to make a bunch of fields public to satisfy Go's encoding package, and code needed to be updated everywhere with a manual find/replace (the same string was used in other contexts too so it couldn't be done automatically)
gofmt has syntax-level replacements. So you could do:
`gofmt -w -r 'unexportedName -> ExportedName' *.go`
or something similar, and it would do the correct thing, ignoring the string matches where it appears in other contexts.
I wish I'd known this a week ago, but I'll keep it in mind for the next time I'm poking at Go :)
and it works well with vim-go integration on vim for example
I haven't gotten very far into the article yet, but this paragraph sent up a huge red flag for me. GC does not make the code safe. All it does is ensure that values don't get destroyed while they're still referenced. But you still run the risk of data races. If you're writing single-threaded code then this is fine (because single-threaded code doesn't have data-races), but the program being written here is a concurrent program.
Obviously you can write safe programs in this fashion. But you still have to think about safety. The difference is the compiler doesn't verify safety for you, which means you can write code fast without worrying about the compiler yelling at you, but your program may have race conditions in it.
Anecdotally, a few years ago when I was active with Go, a program of mine would segfault about once a month. It was a command-line utility that I ran maybe a few times a day. The segfault was so sporadic that I could never figure out what was going on. Then Go 1.1 introduced the data race detector. Using that, I was able to discover that the Go runtime was actually spinning up two goroutines when I thought it was only using one (servicing the stdout and stderr of a child process), and the one buffer object I was writing to turned out to be written to from two separate threads. This usually worked, but on that rare occasion it would lose the race and overrun the buffer. This is a bug that plagued me for half a year, and I'm really glad that the Go team created that data race detector because I never would have figured out what was going on without it. But it's a bug that simply cannot happen with Rust.
<3 Go's race detector (also the deadlock debugging support). Used it quite often though I didn't hit it much.
Agreed, none of this is a problem with Rust :)
Wait, does it mean that go makes your code running in more threads without you knowing? When can that happen? Sounds scary if true.
I don't remember the precise details anymore, but my recollection is I was spawning a child process and passing Writers to use for stdout and stderr (looking at os.exec, I don't immediately see anything that matches my recollection, so I'm wondering if maybe I was using a different package). I expected that it would internally do something like select over stdout and stderr in one goroutine, therefore making it safe for me to pass the same buffer object for both (because I wanted to combine writes). But instead it was spawning 2 goroutines, not 1. And there was no evidence in the API that what I was doing was wrong, the only way to know was for the data race detector to flag it.
One thing that immediately set off my radar (as a Go programmer) is the paintingLoop switch on type.
Yes, sometimes a switch on type is necessary. However, this is not one of those cases.
You want to have a Triangle and Line with a Draw() method and a "Drawable" interface... and then just call into it. The signature of the loop in question then is paintingLoop(ch chan Drawable).
An abuse of naming, but a Quit.Draw() could actually quit, for example. This is just offhand though.
In short, good article, but the Go examples are written with a Rust intuition. Which, I mean, fair enough; I started writing Go with a C++ intuition, with different questionable practices ;)
But yes. It was written with Rust intuition, and whilst I ried to learn the Go way of doing things, I obviously didn't pick up everything :P
Thanks though; I'll try to use this pattern in the future!
I love how "opinionated" and slim Go's design is. The less variation in code, the better, in my opinion. It might not be as "fun", but frankly I have a lot more fun programming when I don't have to deal with esoteric solutions to problems.
Generally using multiple channels and select is good when you have multiple threads sending. When there is a single sender, putting everything in one channel feels better to me.
I never ever have to even touch imports, except sometimes when two different packages have the same name.
var x int
_ = x
Mildly annoying, but it avoids unused variables in any code which compiles, and is a helpful reminder of "I was going to do something with this value".1. Synchronous by default 2. Interfaces
Point 1 to me feels silly to admit. But man, i still do a fair bit of JavaScript/Node for work (our frontend, mainly) and it is just so.. tiresome to me, to constantly feel on the edge of bugs because some functions are expected to be synchronous (return values) and others are intended to callback.
I'm not even talking "nested-hell", i'm simply referring to the mental overhead that i apparently use when using any JavaScript function. It's not difficult.. it's just not enjoyable. It's.. tiresome for me.
Point 2 is simply because i really like interfaces. Back from my Python days, a few libraries had invented ways to support interfaces and i really really liked them, but not the overhead they required. Being able to expect the behavior of an object with certainty is the main part of duck-typing to me, and seeing that from a more static language (when compared to python/js) is really enjoyable.
I know you didn't ask for a writeup, i just had to agree with you and felt the need to share my experience from a similar standpoint. :)
One approach I've been playing with in JavaScript-land is using Promises for all return values, this means that you consistently know how to interact with a return value, whether its concrete-value is available immediately or at a later time -- this doesn't really solve the problem of consuming other people's libraries however!
They seem rather harmless to me, so i'm curious on your perspective. I see them as no more dangerous than an explicit type (or any function, for that matter).
You're asking for a specific behavior, and you know that what you get will have that specific behavior. A Reader or Writer is a simple example of that. Sure, you don't know what it's writing to, but that's outside your scope and likely the scope of the function - right?
Perhaps i misunderstand you, i'd love further explanation/examples _(pertaining to Go's interfaces)_ :)
Pretty much why i never got into node development.
In short, assign nil to a variable, and it ends up not being equal to nil (?!?) Really, how does something like this get approved?
Funny thing: I actually benefit from not typing idiomatically! GoSublime runs gofmt whenever you save a file. It's a free check for syntax errors, as it won't fix the formatting if you made a mistake. And because the mistake must be in the non-idiomatic formatting, it's easier to spot too.
> I'd love to see a rustfmt, however!
Seriously, I miss gofmt in any language that doesn't have a similar feature. I'm so surprised it hasn't been copied more!
For example, if your class is named FooBar and you are declaring a FooBar variable by typing foobar, Visual Studio will just auto-fixit as you type. Same goes for properly formatting if statements, declaring functions required by interfaces, etc... In comparison, Xcode requires you to "confirm" the autocompletion fix by hitting enter, which is less ergonomic in my opinion.
When I started writing python on my own, I dislike some of the PEP8, I liked two spaces, not 4, etc... But then as soon as I started working with teams, my personal preferences no longer mattered, sticking to PEP8 make made life way easier.
I think eventually we'll just store the AST in our version control systems, and use interfaces that we will adjust to our preferences when editing, diff'ing etc...
type MyEnum int
const (
A MyEnum = iota
B
C
D
)https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html...
(rust enums can have associated data too, but its not their main usage in idiomatic code)
That said I wonder why they named it enum.
Because it's a type-safe enumeration? ADTs are pretty much a superset of C-style enums, an ADT with all-dataless constructors is equivalent to a C enum:
enum Foo { Bar, Baz, Qux, Quux }
And members can converted to integrals: > println!("{}", Foo::Qux as u8);
2
With explicit integrals very much like C: > enum Foo { Bar = 5, Baz, Qux, Quux }
> println!("{}", Foo::Qux as u8);
7
Calling it "enum" makes it familiar to C developers[0], "union" would have been confusing for the same (as you can't just write one representation and read the other) and "type" is a tad too generic (and used for type aliases à la typedef).[0] even more so C++ developers as they have `enum class` which is also type-safe and not implicitly converted to integrals
OTOH I haven't written a line of Rust of yet, so enum might be more familiar in use.
type Shape struct {
Rectangle *Rectangle
Circle *Circle
Triangle *Triangle
}
Then you send shapes on your channel rather than interface {}. If you want to enforce having only one element populated, make the struct members private and write: func NewRectangleShape(r *Rectangle) *Shape {
return &Shape{rectangle: r}
}"A circle, triangle, or rectangle" is not the same data structure as "Something that can be drawn". Certainly if you have a function that draws something given a Draw() method, having the function take a "Drawable" is appropriate. But it's not the only use case; sometimes you really mean "A circle, triangle, or rectangle" and in that case, a struct is absolutely what you want.
However, I was writing a rather tiny library so it wasn't a major factor, so I didn't notice this until much later.
I did intend to add a blurb about this when posting to Polyglot Weekly, but I .. forgot ;P
The big new idea in Rust, of course, is the ownership model and its compile time borrow checker. That's worked out surprisingly well. I expect to see that idea appear in future languages. One could have a Go-like or Python-like language with a borrow checker. It's not inherently tied to Rust.
As a practical matter, programming in Rust is more likely to hit problems with type checking than borrow checking. Ownership problems are usually with your own code. Type problems often involve code written by others, and changes to other modules often induce type errors. Because Rust has type inference, and because it's often not obvious what the type inference engine is doing, Rust can have rather abstruse type problems. Go is rather straightforward in that area.
Go lacks generics and templates. This simplifies the language, but the lack of generics then has to be worked around. Go has too much use of "interface{}". Bolt-on compiler passes such as "go generate" and the protocol buffer compiler have been added. Both are used mostly to get around the lack of generics. Rust has very powerful generics and templates, so powerful that they tend to be over-used. Everything seems to need a generic. Rust is starting at the cruft level it took C++ 20 years to reach. This may or may not work out in practice. It may be necessary to restrain Rust template enthusiasts from getting carried away.
Error handling in both languages is via return values. Go is straightforward, with multiple return values being the normal approach. The Rust mechanism, involving Result<> and Some<> types, is rather clever, but results in wordy code to do simple things. Too much Rust code goes into putting things into Result and Some objects, then analyzing and dismantling those objects. It's not clear that leaving exceptions out of Rust is a win. Negative experience with C++ exceptions may have motivated that design decision.
Rust has Resource Allocation Is Initialization (RAII). Go does not. For both languages, problems come up with resource release. Go has "defer()", which is kind of clunky and can't be encapsulated, while Rust has destructors called when something is deallocated. In both cases, it's hard to handle an error at resource release time. Destructors that do anything non-trivial are usually troublesome. Both languages have this problem. Languages with "with" (Common LISP's "(with-open-file ... ...)" and Python's "with FILEOBJ as HANDLE : " have fewer headaches with resource release errors, since they occur in ordinary code, not at some special destructor time.
(I've just browsed the rust docs, never written anythign in it)
fn do_stuff() {
// already inside a function!
{
// allocate here...
let x = Giraffe();
}
// should be deallocated by now. right?
}It would be nice to have a cheatsheet full of Go tips & tricks like gofmt/goreplace for replacing idents, and goimports-on-save, and whatnot. TBH I didn't really look for such non-in-built solutions when starting though, so I would have missed it anyway :P
I can't fault new users for this; the non-discoverability of these awesome tools for new users is a genuine fault of the Go ecosystem.
Just a "Tips" or "Useful Tools" list at the end of the Getting Started page or the How to Write Go Code page would be better. Just to make users aware that such tools exist.
I think it's safely implied that you put more effort into Rust code, but get more out of it. It's a tradeoff from Go. It's worth it for some programs, and others it's not.
Go for me doesn't work out because it's not C ABI compliant which is a limitation Rust doesn't have. As a language nothing draws me to it in particular. The killer feature is how easy it is to get started with it. Something that is undersold.
Coming primarily from Python I'm still favoring the field over Go until my problems matched Google's. I would probably reach for Erlang for concurrency and Rust for anything low-level going forward.
This is pretty much why I consider these two to be in less competition than first meets the eye. Rust intrinsically involves putting more effort in to the code. You put more effort in and you get much more out, but there's a lot of code for which that's not the right tradeoff, just as there's a lot of code for which it is.
"In Go there's no obvious way to get this. The closest thing is the type called interface {} which is similar to Box<Any> in Rust or Object in Java.... Of course, I could implement a custom interface MyMessage on the various types, but this will behave exactly like interface{} (implemented on all types) unless I add a dummy method to it, which seems hackish."
I think most Go programmers stick to interface{}, but personally I put the tag method on the type, being from the Haskell side of the house on that front. In practice it turns out that often the "tag" interface grows a useful method of some sort, at which point it ceases to feel silly. If nothing else, you've got the ".Handle()" option. See also http://www.jerf.org/iri/post/2917 .
Also, just generally on the performance front... developers who care about performance are at this point subconsciously pretty used to being able to choose between "language like Rust or C++ that really, really cares about performance, but is hard to use" and "dynamicly-typed language that's really flexible and powerful but 50-100 times slower than the other choice". In the limit, Rust will absolutely be faster than Go, no question, but the performance penalty may be more like a factor of 2 in the end... Go's pretty fast, and while you can't go absolutely crazy with optimization C-style, you do get to play with locality optimizations with real structs and real arrays and such. Worrying about the performance differences between C and Python before you write a line of code may be perfectly valid, because the gulf is pretty large... worrying about Go vs. Rust is going to be a much narrower band of validity before you're just prematurely optimizing. Rather a lot of high performance code still has "vtables" in it, used quite extensively.
In practice, I don't expect many people to decide between Go and Rust based on performance needs on similar code... non-zero, yes, but not many. What expect people to choose between them are general software engineering complexity considerations. When it comes down to it, the reason to write Servo in Rust and why Rust needed to be created to do it isn't that there weren't languages that were "fast enough"... it's that the browser has bat-shit insane sharing patterns, complexity beyond the mind of any mere mortal, and you end up with code that either does way too much copying or crashes when it doesn't do enough, because there's no ownership management in the language. That's the sort of reason to choose Rust over Go. If you're making something that looks like a browser, or an office suite, or a big highly-integrated business workflow suite, or something like that, I'd choose Rust over Go in a heartbeat simply because Rust is designed to shine in that environment, and Go ultimately doesn't particularly offer anything to make that scale of that sort of code any better than any other statically-typed language.
As far as we're concerned, the most compelling reason for Servo to exist is performance, especially in layout and rendering. Many of the wins of Servo layout have come from carefully coding to the optimizer to allow it to eliminate virtual dispatch and procedure call overhead, break apart structures, stack-allocate where possible, and (in the future) use SIMD. As a result, the performance profile of most of Servo layout tends toward flat loops as opposed to deeply nested stacks of virtual call upon virtual call—much friendlier to the branch predictor, i-cache, and intraprocedural optimizations. At the same time, we get a lot of responsiveness wins from having a threaded design where pauses in one thread—most importantly, JS and the DOM—do not impact responsiveness in the other threads, which becomes very important when CSS animations are involved, especially common ones that require reflows.
Now with Go, we'd have the choice between a compiler that basically doesn't do any optimizations beyond very simple ones (6g/8g) and a compiler that lacks good GC integration (gccgo). The former would negate all of the advantages of our careful coding to the optimizer and would probably make Servo layout, in parallel mode, slower than the sequential layout of other browsers. (Despite what djb says, compiler optimizations really matter!) And the latter would cause the stop-the-world GC times to spike, jeopardizing our smooth animations, which arguably matters even more than raw reflow performance to the user experience. (That's not even counting the fact that since Go's malloc is reportedly extremely slow compared to that of Java, it relies heavily on escape analysis, which gccgo doesn't do…)
There are other reasons too, such as the fact that integrating a good JS garbage collector and Go's garbage collector would basically be impossible without rewriting one of them and making major sacrifices along the way (like making JS GC multithreaded or making Go's GC conservative, like Blink did with Oilpan). But performance is the main reason.
Yes, but if that were the only concern, you wouldn't need Rust to do it. C++ already exists, and it can do all those things. (Well, the "break apart structures" may be a bit unclean depending on exactly what you mean, but that alone wouldn't be worth writing a new language for.) My interpretation of C++'s raison d'etre in modern times is "zero-cost for abstractions you don't use", whatever its heritage may have been in the past. If that were the whole story, you just would have started a new C++ renderer from scratch.
You need Rust because actually writing that code in C++ would be unmanageably complicated due to the ownership problems that Rust addresses. C++ is already unmanageably complicated (IMHO) when trying to write a browser engine, also requiring that level of performance would basically take it into the realm of the impossible.
You need the complexity management first. Managing the complexity buys you the cognitive budget to write the fast code, too. It is not as if the C++ render authors do not want to write fast code, or as if they are unaware of the recipe you just laid out.
I said I wouldn't write it in Go because it is already disqualified due to the complexity issues. Even if I didn't care about the performance gap, I still would have no desire to write a browser engine in it because it would be a nightmare, just like the C++ engines are, and for pretty much the same reasons, in addition to others. The performance gap between Rust and Go here is essentially unmeasurable, because in this task, Go won't even cross the finish line. (By my standards, at least. I consider the C++ renderers to also not cross the finish line. The fact that memory-unsafe code can be bashed into submission with sufficient man-millenia doesn't mean I have to agree that memory-unsafe programming languages are a good idea.)
More importantly, there isn't any language that focuses on _making SIMD work right_ -- even C/C++ do an awful job of this with it's tacked-on __mm_foobar functions.
Rusts idea of having SIMD live as near-primitive datatypes (f32x4 etc) follows Dart a bit and overall I think it's a good approach -- albeit very incomplete right now.
I seriously hope that emphasis will be placed into making SIMD feel like a first-class citizen in the language and not a tacked-on feature as I've seen in so many other languages.
Whether or not you can afford this very much is an upfront thing. You cannot push something like this off until later. For things like a web browser or game engine or other highly-interactive, highly-latency-sensitive, high-ram-using thing it's known far in advance that the GC will be a curse.
This is why C++ continues to be the language of choice for those sorts of systems. Control over memory is crucial for them.
> ... there is no other language I can think of with such a small surface area that I can tell students in the first week to learn and deliver an assignment by the second week
...
> This is pretty much why I consider these two to be in less competition than first meets the eye. Rust intrinsically involves putting more effort in to the code. You put more effort in and you get much more out, but there's a lot of code for which that's not the right tradeoff, just as there's a lot of code for which it is.
I don't consider the two to be in competition (aside from "which hip new language should I learn today") either, though it's less due to the easy-to-pick-up thing and the Rust mentality that:
- If it can be a footgun, be explicit (unsafe, exhaustive matching, unwrap)
- If you can do it at compile time, DO IT DO IT DO IT DO IT (all the compiletime type safety, ownership, etc). All abstractions should be zero-cost or with minimal cost (at runtime). Try to write your code so that tests won't be necessary (because a successful compile should be a test), and then write tests anyway!
(This mentality is pretty prevalent in both the Rust stdlib/language and external libraries. The equivalent of interface types in Rust (`Box<Trait>`) is generally frowned upon and only brought out when absolutely necessary, for example)
Go doesn't really embrace either of these principles, so it doesn't compete that way. You're right, developers already are used to making those choices.
> worrying about Go vs. Rust is going to be a much narrower band of validity before you're just prematurely optimizing. Rather a lot of high performance code still has "vtables" in it, used quite extensively.
Not necessarily. As mentioned before, the Rust way of doing things generally leads to a lot of optimized stuff. Taking the vtable example -- Go code that I've seen uses vtabley things everywhere (the stdlib is peppered with interface types). Using vtables isn't bad, but when you use it for stuff that could have been solved by static dispatch (for large codebases -- that can be everywhere), then it can become an issue. In Rust a vtable is a last-resort that people will grumble about before picking up and using (but will use it whenever absolutely needed). Sure, a single vtable isn't much of a performance optimization, but when all your APIs use static dispatch due to this mentality, the collective optimization is huuuge.
> In practice, I don't expect many people to decide between Go and Rust based on performance needs on similar code... non-zero, yes, but not many.
For many applications, I agree. Systems programming is one where this doesn't apply, but for stuff like a distributed consensus algorithm implementation (which I was doing), both Go and Rust are perfect. And I'm pretty sure that if I'd had more practice in Go, I would have been confused which language to write it in. (Right now I love Rust and am not great at Go so of course I would use Rust if given a choice)
For stuff like a browser, it's not so much that there are batshit insane sharing patterns, it's more because a browser is huge and performance matters a LOT. (I think pcwalton above explains why better than I can)
As a lecturer, Python would be my other choice, nowadays, for a small surface area language.
I suspect Go has the advantage here simply because it barks at you at compile time over certain errors. Pedagogically, something that students have to run that checks the syntactic validity of their program is probably win.
I emigrated from Lisp->C->Tcl->Perl->Python over about 30 years and Python is still the thing I reach for when I have to whip up a program (yeah, Lisp was nice but I could never afford a machine with enough memory for it not to be a toy--memory was expensive at one point, you youngsters).
Go doesn't really interest me that much. It's a little better at a broad range of things, but nothing that pulls me from the existing set of languages. I'd rather use Erlang for concurrency, for example. Maybe if I had Google-sized codebases I'd care more.
Rust interests me because it is in the same range as most languages for most things but is a LOT better at a very few things.
I'm waiting to hear somebody use Rust in a video game engine. I suspect that C++ will vaporize (one can hope) once someone proves that Rust works in production.
I too am a Python fan for scripting though :)
> Rust interests me because it is in the same range as most languages for most things but is a LOT better at a very few things.
Me too, for similar reasons. It's like C++, but without all the stuff I didn't like about C++ :)
> I'm waiting to hear somebody use Rust in a video game engine.
Yes, but by definition, we're discussing optimized code here.
http://benchmarksgame.alioth.debian.org/u64q/benchmark.php?t...
Yeah yeah, benchmarks blah blah, but the point here is, compare with, oh, say, this:
http://benchmarksgame.alioth.debian.org/u64q/benchmark.php?t...
As I said and will repeat without blinking, Rust will always be faster than Go (and the problem in the shootout Go beat Rust on is in my opinion certainly simply an unoptimized Rust implementation, no question), but language deltas of 2x or 3x in practice are dominated by algorithms and IO far more often than 50-100x. For all the long list of reasons that Rust is faster than Go, all of which are true, they add up to much less than developers are used to. Intuitively, when you hear "go is slower than Rust because vtables and bad optimization and GC and its pauses and interfaces" you probably mentally expect Go to be like 10 times slower, when instead it's 2-3.
This is relevant because I don't think Rust advocates should sell "speed!" too hard as the primary thing they have... C++ will pretty much forever be able to keep up on the raw speed front, especially in benchmarks. What it has is complexity management, at speed. But complexity management first.... Rust could probably take a straight-up 2x speed penalty over C++ and still write a renderer than ran faster than C++, because it'll be a better renderer.
Scotty! We need more CORE[s] !"
Sounds like an awesome professor! It's a pity he didn't get you to use Nim.
Kudos.
Bonus, you can define "tolerable minimum" and "nice to have" versions of the same local interface. Define your methods in terms of the first, but attempt to cast to the second.
if nice, ok := minimal.(Nice); ok {
// do stuff only possible with the nice to have interface
}
Example: the HTTP libraries will flush your IO if you give them something flushable, but they don't require it. _ = unusedVar type Color int
const (
Red = iota
Blue
Green
Sausage
Yellow
)
The `Color` type is not compatible with int, so except for explicit casts and literal assignments, it's type safe.Though that's quite a different enum style compared to the tagged unions of Rust, his approximation with interfaces is indeed closer to that.
Should be "switch msg.(type)" instead of "switch ch.(type)"
> This rules out some workflows where I partially finish the code and check if it compiles.
Sounds like a great job for an IDE to automatically add/remove the appropriate imports for standard library stuff.
The only time in my experience that it has trouble is when there is a namespace conflict and it has to guess. Generally that's easy to avoid though, and uncommon.
EDIT: downvoters, please explain what's wrong with my comment.
Go interfaces are quite a novel concept, and most developers that jump from language X to Go don't have enough time and experience to understand how they work, and how to design their application around this new model.
Their example of the messaging system/UI application is a straight port of the Rust code, and they lament the fact they have to use interface{} to overcome the lack of object orientation or pattern matching.
func paintingLoop(ch chan interface{}) {
// shorthand for a loop over receiving over
// a channel
for msg := range ch {
switch ch.(type) {
case Quit:
// quit
case DrawLine:
// cast to a drawline message
line := msg.(DrawLine)
// draw `line`
case DrawTriangle:
tri := msg.(DrawTriangle)
// ...
case SetBackground:
bg := msg.(SetBackground)
// ...
default:
// Need a default case in case
// some other type is fed through here.
}
}
}
This is not idiomatic Go. The author here should be leveraging Go interfaces and they wouldn't lose type safety. type Drawable interface {
Draw()
}
type Line struct {
x1, x2, y1, y2 int
}
func (l *Line) Draw() { ... }
type Circle struct {
cx, cy, radius int
}
func (c *Circle) Draw() { ... }
func paintingLoop(ch chan Drawable) {
for object := range ch {
object.Draw()
}
}
func main() {
ch := make(chan Drawable)
go paintingLoop(ch)
ch <- &Line{x1: 10, y1: 10, x2: 50, y2: 50}
ch <- &Circle{cx: 10, cy: 10, radius: 20}
}
You wouldn't expect Python programmers to try Haskell over a weekend and have enough experience with it to write a blog post about "Thinks I dislike about Haskell", but it seems much to often people play with Go and, when they fail to translate their ideas to this new language, post yet another "rant" on HN about how Go sucks.Go has its fair share of shortcomings, but try to _learn_ the language before writing yet another misinformed article.
But point taken. I will try to use this pattern in the future.
> Go has its fair share of shortcomings, but try to _learn_ the language before writing yet another misinformed article.
I believe I was pretty clear in the article that I didn't know the Go way of doing things and this was about what Go looked like from a Rust point of view. This was not supposed to be a rant, just a post that sort of illustrates the differences between the languages. IMO it actually gives a clearer idea of what Rust is like than it does of Go since the "Rust way" of doing things is clear from the comparisons..
They're not: https://realworldocaml.org/v1/en/html/objects.html#ocaml-obj...
> This is not idiomatic Go. The author here should be leveraging Go interfaces and they wouldn't lose type safety.
You've conveniently ignored the case of the non-drawing commands. Should they be Drawables with a Draw which does not draw anything?
> Go has its fair share of shortcomings, but try to _learn_ the language before writing yet another misinformed article.
The OP has been upfront about his limited knowledge of Go, and his rust knowledge coloring his thinking.
In particular, you can't implement Quit using a virtual method, unless you do something like have every function return a boolean to the caller indicating whether it wants to quit (or panic and recover, but that's too awkward for words).
You also can't have methods that set local variables in the caller, unless you do something like pass in their addresses to the function, which gets awkward quickly if you have a lot of local variables.
How would you do that using ADTs?
That doesn't mean the article isn't interesting or useful though. It's helpful for any language community to see what a new comers first impressions are and then tailor the onramp appropriately in their documentation.
You are unneccessarily hard on the author here I think.
This assumes the structs themselves know how to draw. This is usually (not always) an antipattern, because it conflates data with behaviour.
I should be able to swap out the drawing implementation without having to change the data. For example, given a circle (cx, cy, radius) I should be able to draw it using SVG or OpenGL.
The enum way is not necessarily "unidiomatic Go". Even if you have something that turns data structs into "strategy" objects that know how to render, you need a matching statement, or you need to build something like a "map[Type]Drawer", which is in my opinion less elegant.
This allows developers to quickly say "I know Go. Here's what's wrong with Go." since they believe they have learned all there is to know about it. This is good, since that's part of why Go is approachable.
However, this has downsides. As you showed, there are succinct features that can make the difference between "this is a bad thing" and elegant code.
OK, it seems I'm trying hard to defend Go. I like it, I seldom (but do) miss generics, I miss some Haskell/Rust features and wish it were a little less simple. But I don't understand why there are dozens of similar "things about Go" articles posted every week on HN, all repeating the same stuff.
The one from Evan Miller was both entertaining and in-depth, but that's the exception.
Our comments are ultimately feedback. We're a community and we want constructive feedback to help each other learn. When giving feedback, just remember to be constructive and consider how your tone could be perceived. I'm sure that you had the best intentions but the undertone of the comment read to me (and many others) as very cutting/attacking.