109 points · by ingve · 4y ago · 180 comments
Not having data races is one of the key benefits of using Rust, “fearless concurrency” and all that. So by throwing away a key guarantee of Rust (no aliasing mutable references), it can become easier for learners to program in. It becomes a bit of an apples and oranges situation at that point.
1. Using a placeholder (let/var/val/auto/...) -- e.g. in modern C#/Java/C++/Kotlin -- and letting the compiler figure out the type, but keep the actual type known at compile time. This will give you compile time errors when using the wrong types, and keeps the variables of a fixed type.
2. Effectively making all types variant types that can hold any value and can change their type -- e.g. in JavaScript/Python/Ruby -- such that they are dynamically typed. This can lead to runtime errors.
For languages like C#, Java and the derivatives, they have the concept where all objects are instances of a common type. If you use this -- especially in collections -- you can also get runtime errors. As long as you stick to the generic versions of these, the compiler will enforce the type safety.
The statically typed languages have been making types optional where the compiler can deduce them to avoid redundancy and duplication. If there is an ambiguity, the compiler will omit a compiler error. This is the best of both worlds -- type safety without the noise of annotating types everywhere.
I think this research highlights a important strategy to make all software safer.
A quote from the discussion section:
> Encouraging adoption of safer languages by reducing stress.
In that sense, adding a gc to rust for single threaded programming, is almost useless : it's not helping that much and you're not learning.
When I have started with rust I was not writing stuff with Box/Rc/Arc... or even explicit lifetimes. Not saying that I was cloning everything but for simple stuff you can come long way with just moving and simple borrowing.
For an already experienced programmer, it's hard not to think about using multiple threads, even when just starting in the language. I know my few first Rust programs were using multithreaded constructs and I found that especially easy to do safely in Rust (when I started, there was already crossbeam and rayon, both making a lot of things easier).
Why not? I mean, maybe not your first ever programming language, but - why should you not get used to doling out work to all available threads to begin with?
If you don't or are unsure about that, then stick to simpler forms of programming or use type-hinted Python instead.
This would the recommendation I would make to anyone asking me that question !
Exactly. Lifetimes, borrowing, etc. are the complexity of thread safety. It's like saying that airplanes are easy to fly, if you replace the airplane with a car.
Having different levels of abstraction within the same language can be really useful.
But you don't want to overcomplicate the language to support that, especially if it makes operating at different levels more complicated.
In this case, it seems like an odd tradeoff to make. The less sophisticated user is exactly the same kind of user that is more likely to foot-gun themselves with a memory or thread-safety issue. The "right" answer is probably a thread-safe garbage collector, but that has its owns set of usability and implementation tradeoffs.
I think it's often pretty easy to not footgun yourself with thread or memory issues, because these issues simply don't exist in wide swaths of application.
(There are limits, though: if you map the same physical addresses to different virtual addresses, Rust can't help you. However, that is independent of threads/processes, because you can also do that in single-threaded programs.)
Hence why I try to make a point that comes with a footnote.
Rust is after all supposed to target all kinds of system programming scenarios.
Are you talking about databases, services or IO and such?
Even Python has it: https://docs.python.org/3/library/multiprocessing.shared_mem...
Locales.
Quite a few other POSIX bits, really.
Of couse it will require nightly since auto traits are not stable.
That's why the entire approach is flawed: They didn't study "Rust + GC", but effectively created a new language. See [1] for more details.
Personally, as someone who uses Rust professionally, I believe optional GC would be a great addition to Rust! The compiler would provide support for GC, and the actual GC runtimes would be library-based, similar to how async/await is handled. However, this GC would merely replace Arc/Rc, not Mutex/RefCell/Cell.
[1] https://users.rust-lang.org/t/bronze-gc-and-aliasing-problem...
And I think Rust would be a much better target language for such a system than C++ was. For example, one of the interesting problems was that the .NET GC is compacting — it will move objects around to improve cache locality and simplify the allocation algorithm. To interact with ordinary C++ code, you need native pointers into GC’d objects. But it was only safe to take such a pointer while you told the GC to temporarily “pin” the object in memory, otherwise, your pointer could be randomly invalidated. Forgetting that step was a very evil source of nondeterministic memory bugs. It’s not hard to see how the borrow checker would help there.
Much easier than dealing with P/Invoke declarations or dealing with COM over RCW/CCW layer.
I'm convinced Rust is easier to write without the management of lifetimes in a short time span. However, what about long term maintenance, and application stability?
Rust with a GC probably has its uses (compiled language with strong error checking), but one has to know what ship they are boarding.
It also makes it quite closer to D, an "easier C++", compiled language with a GC.
(I'm saying this as someone who tried Rust, and mostly uses GC'd languages)
edit: thanks for the replies below. I hadn't though about this. I guess one should better read my message as "If you remove Rust's lifetime management, …"
I want it to be exactly clear what I'm saying... While you (the programmer) may understand when an object is destroyed, and Rust (the compiler) will agree with you, that information is not present in the type system and you cannot use it in your programs. In this aspect, Rust has the same problems as C++... but where C++ still lets you write code, Rust will just throw an error and force you to use "unsafe" here.
Yeah that's the problem with all these studies that use students writing new code for a few hours.
99% of coding isn't like that - it's reading other people's code (including code you wrote ages ago and can't remember), trying to figure out how it works, following complex call chains, debugging etc.
If you only look at Advent of Code type problems you'll come up with all sorts of strange conclusions, like static types don't make a difference, comments aren't useful at all, it doesn't matter if you exclusively use single character variable names, goto is totally harmless, etc. etc.
Though in this particular case I guess they didn't have much choice because there are no existing large programs written using Bronze.
One example in my head individual strings that need to be constructed dynamically but live for the lifetime of the application (better to leak it with Box::leak or lazy_static! than pollute all code with lifetimes)
Another is writing in lifetimes for single purpose objects that live on the stack and might only ever get passed by ref into a single function and then get destroyed soon after.
Lifetimes are super important in rust and are a core part of the language, but in such degenerate cases they take up a lot of programmer effort for little benefit. In my head a "automatic" solution such as GC /could/ have a home in the language. Perhaps this would make rust a slightly better fit for really complex monolithic GUI apps (word processing, spreadsheets, CAD) where full GC would be performance-onerous but data lifetimes would be too complex for rust's strictly ordered lifetime concept
That's exactly why I loved D over C++ and Rust and had the feeling that I was not fighthing the compiler from day one: the GC, auto types, lack of annoying C preprocessor.
This actually made me chose D over Rust for my last project.
This makes me happy to use D instead of Rust. D has a @safe subset.
Obviously it won't leak memory if you do it correctly, but Rust will happily let you leak memory in an Rc<T>.
It reminds me of the longbow vs crossbow.
One is a technology that anyone can learn to use easily, the other is one that takes longer to master, but is a more efficient weapon in the hands of a skilled soldier.
The analogy isn’t perfect but the parallels are there.
http://www.thebeckoning.com/medieval/crossbow/cross_l_v_c.ht...
Instead there is plenty of evidence that currently there is a lot innovation in all niches of the programming ecosystem - from low level [Rust] to high level, and a lot of coder interest in all the options.
Also talking about "lowest common denominator" comes across as somewhat snobby - many world-class coders use high-level languages when appropriate. It's a matter of choosing the right tool for the job, not dumbing down.
Consider the popularity of Javascript and Electron for Desktop applications.
Your example cherry picks exactly one instance, ignoring the context of that choice. Such an assertion requires more than just anecdotal musings and ignores the tradeoffs that those teams made when choosing a platform.
I don’t want to make a “Windows app”, “A Mac app”, or a “QT app”. I want a rectangle and a high-level enough interface to build my own widgets. People who are single mode users obviously hate that every app looks and behaves different but most people are multi-mode and don’t care.
JS is only easy at the most superficial level and gets to be a mess once you go beyond small apps.
In some cases, but there is definitely a trend of dumbing down stuff in the name of accessibility or ease of use. As long as the GUI does not limit me and I can still tinker with various stuff under, say, "Advanced", I am okay-ish.
And yet the folks maintaining the network stack in the Linux kernel are not anywhere near what I or almost anyone else would consider the lowest common denominator programmer.
Sometimes you just have to accept that ALL humans are inherently bad at this, only some are worse than others at various points in their lives. The security and reliability of the product of our output should not be so largely dependent upon our ability to get a full night's sleep, reasonable working hours, and lack of personal conflict. To be sure, we should all strive for those things, but perhaps the choice of tools is correct in prioritizing mitigation of difficulties and vulnerabilities from meatspace.
Sometimes that's a borrow checker. Other times it's a garbage collector. And every once in a while, we need to break out an unsafe block (or the entire C language) to get a job done.
Considering how much more expensive people are than software or hardware, the trade off for easier/simpler access is increasingly straightforward.
Which is prioritizing a lower barrier to entry for new programmers at the cost of safety checks that help prevent humans from making mistakes at runtime.
It seems to me if our conclusion is humans, no matter how skilled, are flawed, we should be willing to do absolutely anything to lower the barrier to entry except removing checks on correctness.
I think there can be an unproductive temptation to use a language as gatekeeper of a culture. If you want a culture with shared values about how to do things, there are plenty of ways to do that other than keeping the language from accommodating anyone outside of that culture. And your culture will be more accessible to people who genuinely belong in it, if it's visible from the places they already live (e.g. the Rust language).
The languages you dislike are popular because they make it easy for everyone to contribute, and as a result they have a bigger community and, perhaps even more importantly, a greater breadth and depth of libraries and packages than competitors. Rust could be competitive with these languages if it had a low floor and a high ceiling of admissible code quality and sophistication.
I use Rust to write CPython extensions... it's a well-known fact that GCs are solitary creatures and you're in for a lot of hassle if you want two different GCs to play nicely together.
I use Rust for all sorts of things because I like the high floor Rust sets for the crates I depend on, and I pair that with being more likely to rewrite or find an alternative for a dependency that uses `unsafe` in a context I don't feel it's merited.
A lot of what the borrow checker brings is fundamentally about requiring the programmer to be more precise about what they intend, rather than patching the cracks with extra CPU/RAM or waiting until runtime and hoping it won't come up.
My main concern here is the risk of Rust running into a more minor version of what happened to D, where you effectively had two language ecosystems and the one with a GC and all the libraries wasn't an alternative to C or C++ and wasn't a very appealing alternative to Java.
I thought this was kinda obvious. Reasoning about borrowing and lifetimes is hard if you've never done it before. But the real question is how long it takes users to learn it and what we can do to improve that. I wonder how close the plain rust users' times would get to bronze users over time as they keep doing similar tasks.
This is the real question for me. The rest is just implementation detail. Someone is (usually) paying for the code to be written. Are they getting more value for less spend over time?
When you look at it through this lens though, there tend to be bigger overriding factors a rust compiler (or any other choice of language) can’t really help with - e.g. is the design & architecture of the code heading in the “ball of mud” direction. I.e. is change velocity going to reduce over time?
With a garbage collector, yeah you most likely are getting more productivity out of a developer. You’ve delegated one of the hardest problems (when can i free this thing?) to the computer. Because of the way rust is designed, it doesn’t protect against memory leaks. It protects against use after free but not that i fail to release redundant memory. But unfortunately It’s not guaranteed that just adding a garbage collector will help with this. With a sufficiently good developer though, they should be able to move faster than if you make them Arc<> & lifetime everything themselves. It’s specifically the lifetime bit that consumes time / developer productivity. Using Arc<> isn’t hard or arduous in any way.
To some degree for me this is *more* important then the memory handling aspects.
For example the whole "collection modified while iterating over it" situation can easily become a nightmare, especially for new programmers. It also does happen in non multi-threaded code all the time (if there are some "cross-cutting" concerns). In many GCed languages/libraries running into this situation is "safe" but unspecified. Worse if it happens to work in some situations (it often does) it's not rare for programmers to rely on this behaviour. That is until it gets subtitle broken due to other code changing, or the library changing. In rust this problem is not a thing, the borrow checker prevents you from accidentally running into it by accident. If you need it there are ways to still get it, but now with well define characteristics. So while this is initially more work, it is much much less bug prone and easier to maintain.
And that's just one example.
The borrow checker might be more initial work, but it often makes you write better, less buggy, easier to maintain code independent of memory management.
That is if you don't get over-obsessed with never cloning, never using Rc/Arc etc. then you are in for pain. Being over-obsessed with only using borrows is a form of premature optimizations. (As a side note even with clones/Rc/Arc the borrow checker still helps you as it's not the same as replacing it with a GC).
And on the other hand, optional GC is something non-GC languages can end up adding too, like C++. Garbage collection is required (or convenient) for some problems, cleaning up objects that would be leaked by reference counting or weaker strategies.
EDIT: deemphasised universality of this rule, not really important to my point anyway: that GC/non-GC memory management are more orthogonal than they appear from language feature discussions, in theory. I wasn't trying to imply literally "all" such languages add these features, I have just noticed a number of relevant cases.
And on the other side, I’ve still never seen a production C or C++ codebase which used a garbage collector. The closest I’ve seen is refcounting - but that’s a very different beast compared to what V8, .net, Go, etc do internally to garbage collect objects.
The only languages I’ve seen which mix GC and non-GC code are D, Nim (I think), with an honourable mention for Obj-C / Swift’s ARC. But again, I’m not sure ARC belongs in the same category as the generational GCs we see in the JVM and others.
With a few obscure exceptions, it seems to me that the gc/ non-gc line is still pretty firm for most programming languages.
There are tons of languages that allow that, even if many of them failed to gain mainstream adoption.
- Mesa/Cedar (https://yahnd.com/theater/r/youtube/z_dt7NG38V4/)
- CLU
- Modula-2+
- Modula-3
- Oberon
- Oberon-2
- Oberon-07
- Active Oberon
- Component Pascal
- Oberon-V
- D
- Nim
- Swift (RC is a GC algorithm, chapter 5, https://gchandbook.org/)
- Eiffel
- C++/CLI
- Unreal C++
- Linear Haskell (getting there still WIP)
- Pony
I kept Nim and Swift for completion as you already mentioned it before.
At least the Inkscape vector editor uses the Boehm garbage collector [4]. There are several programming language implementations which use Boehm and C, but one wonders if it is still a "C codebase" then.
[1] http://www.lispworks.com/documentation/HyperSpec/Body/d_dyna...
[2] Henry Baker, CONS should not CONS its arguments https://www.cs.tufts.edu/~nr/cs257/archive/henry-baker/cons-...
[3] https://youtu.be/5uljtqyBLxI?t=791
[4] http://inkscape.gitlab.io/inkscape/doxygen/namespaceInkscape...
But I was specifically responding to / confused by this claim in the GP comment:
> GC-based languages all ended up adding special syntax to add that level of control for objects when the programmer wants fine-grained control over the destructor. (Emphasis mine)
And as you say, Java, V8 and Go do this with heuristics, not syntax. And I’m not sure if Ruby or Python do this sort of escape / generational analysis at all. On the flip side, it looks like Lua has added something like this, and C# has stack-allocated structs.
Lua + C# + CommonLisp falls very short of the “all GC languages” claim.
Languages tend to have workarounds or conventions for this kind of code where there isn't special syntax for it: https://stackoverflow.com/a/865272 (Python)
Also just because C or C++ codebases don't use GC doesn't mean it's not useful. I've never used it either, but I can think of situations where I would use it. Like I've not used most of the algorithms I learned at uni but I can still think of where I might use them.
If you allocate a value to return, you don't in general know how it will be deallocated because that depends on the caller. The caller may use it for a short time (so stack allocation could work) or store it in the heap where it will have indefinite lifetime. This is why it's not implicit from the scope.
Data flow compounds the problem: if references to arguments to the function are stored in the allocated return value, then the return value extends their lifetime, but again, the writer of the function doesn't know by how much.
Simple refactoring which abstracts code into more reusable functions will obscure local reasoning about allocation.
Working around these problems in the absence of GC or lifetime analysis means adopting various ad-hoc fixes, like calling conventions which pass the location for the return value as a hidden parameter, or smart pointers which dynamically track ownership, or coding conventions like caller always allocates, or global conventions like zone allocation.
The big programming ergonomic side-effect of the presence of GC is the ability to more freely write and refactor functions that allocate and freely reuse them elsewhere. Conversely, code written without GC will be less factored into reusable functions.
Rust's lifetime management is somewhere in the middle. It requires particular conventions and if you're able to follow the conventions then ergonomics approach that of GC. But if you want cyclic data structures, or to simply pass data which might enable the construction of cyclic data structures, you need to think harder.
Well, this paper starts off with a bang.
A quick search on github returns this repo [1] by mcoblenz who I assume is the first author Michael Coblenz. Unfortunately nothing but the readme has been updated in 10 months and I couldn't find a link to the latest source with a skim of the paper and bibliography.
I would say the borrow checker makes rust harder to learn, but it does not make it harder to use once you actually grok it. When that time comes, the borrow checker fades into the background. When I got to that point with Rust, it became much easier to use than other languages for me (others I use being C++ and C).
This seems to be at odds with the paper, which describes it as mark-sweep?
> This implementation is experimental. The 'main' branch has a collector, but it only works in limited cases is not general enough to work with YOUR code. The 'API-only' branch has the collector disabled; be aware that you will eventually run out of memory. However, the present version is suitable for experimentation and prototyping.
It's possible the team behind this may have hoped to use the study as part of a grant proposal to get funding to build out a more robust GC for rust.
I may be a bit sheltered, but this was my first exposure to a study with so many volunteers completing involved coding tasks to assess language features.
I find Figure 3 to be particularly convincing: http://shitmyself.com/image/figure3.png
Why are you posting a link to a page which requires authentication?
I added an exception for images and then overwrote the config with a previous version... -_-
Should be fixed now.