163 points · by emschwartz · 3y ago · 173 comments
Both `&` and `&mut` can be moved to another thread (through only `&` can be used by multiple threads). This holds even if the livetime is not `'static`, but requires the usage of a scoped threads API which use a trick to assure that the sub-thread(s) can not outlive the parent thread from which the `&`/`&mut` comes.
Originally such an API was in rust/std but it was removed as it was found to not be sound in the way it was implemented, but sound versions of this API do exist(1) since a long time as libraries and there have been efforts to move it back into std (but I don't know the state of it).
(1): For example crossbeam::scope : https://docs.rs/crossbeam/latest/crossbeam/fn.scope.html
Without scoped threads this means all references you want to give to a thread must be allowed to live forever, the lifetime 'static, since your threads might live forever (the mechanism to kill them could be discarded unused somehow). Since scoped threads always cease to exist when they go out of scope, we can give them references that live any time longer than that scope.
This happened to be useful for something I was doing at work where the wrapper for a native C library expressed the required lifetimes of the library constructs using lifetimes. (Eg. You must set up Foo before Bar, and Foo must outlive Bar. It was OK to pass Bar and use it from multiple threads, but it had a lifetime attached. Using scoped threads we can satisfy the compiler's lifetime checker, since it knows even though we gave Bar to many threads, none of them outlive Foo.)
Most importantly it works with references like `&`,`&mut` or `Cow` etc.
E.g. in the example below it use used to ad-hoc implemet a typical simple parallel fold pattern where a collection of data points is chunked and split across num_cpu threads where each chunk is processed in parallel followed by combining the results.
https://play.rust-lang.org/?version=stable&mode=debug&editio...
Now in practice for many use cases you want to use more convenient/optimized libraries like rayon for this kinda of things instead of ad-hoc implementing them by hand.
But having the necessary primitives to implement it ad-hoc yourself without unsafe code is grate anyway.
Take the first two sections as a perfect example. You decide you want to introduce a single-character control symbol `&` (which is questionable by itself), how do you apply it? In one case you decide that this control symbol indicates that a value is immutable and in another it's part of the declaration of a value as explicitly mutable. You've now introduced a semantic contradiction that a learner has to overcome.
Now obviously Rust works, and that's its point, and people love that enough to overcome all the ergonomic challenges the language puts up. What I can't wait for is Pythonic Rust where we have a language that treats humans as first class citiziens but offers the guarantees that Rust does. The only question in my mind for if this will ever happen is if the fully literate programming modality enabled by LLMs will make it a moot point.
let a = 1; // a is immutable
let mut a = 1; // a is mutable
Then a bit further in they will learn about references, and that there are two kinds of references: a: &i8 // a is a immutable reference
a: &mut i8 // a is a mutable reference
I believe it is pretty clear that "mut" is what signals mutability, while "&" signals that something is a reference. There is next to no reason to associate "&" intrinsically with mutability, since you will have seen "mut" in a non-reference context and you will have seen "&" in a non-mutable context.If learner is unfamiliar with the very idea of references, then his/her problem is not an ampersand, but how to grasp the distinction between reference and value.
Rust makes it hard, because it takes its own view on how variable relates with its value: Rust variable holding a value behaves much more like a reference to the value than a variable in C does. It is hard to notice with Copy+Clone types, like integers, but it bites in the ass with others. Variable in C is associated with its memory. When you write `int a;` you create a variable which has `sizeof(int)` bytes of memory. It doesn't work with Rust, a place in memory is an attribute of value not of variable. `let a: i32` doesn't allocate memory, memory will come with a value, when you assign the value to `a`.
I mean it is hard to grasp at first. I came to Rust from a C world, and struggled to get this simple fact for a few months. It seems stupid in retrospect, it was written all over the place in Rust Book, but my mind took the relationship between a variable, memory and a value as a kind of an implicit dogma, and failed to notice how it breaks in Rust.
But I digress. So variable in Rust has some properties of a reference. And then there are "real" references like &, &mut, RefCell, Rc/Arc. These didn't made my life harder, they work like my C-mind expected them to work, but I assume that people who come from a higher level languages can struggle to grasp all the differences.
> Take the first two sections as a perfect example. You decide you want to introduce a single-character control symbol `&` (which is questionable by itself), how do you apply it? In one case you decide that this control symbol indicates that a value is immutable and in another it's part of the declaration of a value as explicitly mutable. You've now introduced a semantic contradiction that a learner has to overcome.
Here you write:
> The author then explains `&var` and `&mut var` not in terms of their nature as references but in their aspects of mutability.
- The angry, tired dog was running
- The angry dog was running
Does the “angry” cause confusion when trying to understand what “tired” means?
`&` never has anything to do with mutability. Only `mut`.
There is no “semantic” contradiction. “Weltschmerz” is a word, and “Welt” and “smerz” are two other words; the fact that they can occur in a compound noun doesn’t mean that “Welt” and “schmerz” by themselves get contaminated by each other.
The fact that they chose to use `&mut` is… syntactic. The semantics would be the same if they used `& mut` or `reference mutable` or `reference which is mutable`.
I’ve sprinkled some ampersands around Rust code in my little time but never because I was confused about how it interacted with mutability.
const a = 1; // a is immutable
auto b = 1; // b is mutable
const(int)* p; // pointer to const
int* q; // pointer to mutable
There's no new syntax, the borrow checker just adds a layer of checks.I think from a PLT perspective, the interesting question is 'can the problems Rust is supposed to solve be resolved in a simpler (but radically different) conceptual model'? We started off originally with a spatial conceptual model -- stack, heap, scope -- that mapped lifecycle semantics to spaces and transitions between spaces. Concurrent programming stressed out that model and we're here with explicit mapping of semantics by the programmer. I've been wondering lately whether a new spatial approach can yet again simplify matters.
I've been closely following the development of Vale since I first saw it here. Though their approach is slightly higher-level than Rust and requires (some) runtime safety checks (though to be fair, so does GC).
https://verdagon.dev/blog/zero-cost-memory-safety-regions-ov...
I think it would be tough to change the spatial model in a language as low-level as Rust, because that spatial model is just reflecting how your CPU actually works under the hood. If you try to hide that away, the programmer is going to end up losing some control.
For a while I was thinking of the question of "Why didn't production rules (a.k.a. expert systems, business rules engines) catch on as a general approach to programming?" Systems like that can do some remarkable things, similar to Excel and logic programming in that you can write programs that aren't concerned with the exact sequence of events that things have to be done in. This is not only convenient for the non-professional programmer, it makes some "chicken-and-egg" problems in conventional programming languages trivial, back in the 1980s people would have seen this to answer to parallel programming, today we might see it as an answer to the async choreography hell of front end programming.
The thing is that sometimes the order of events matters and when you look at rules engines they never settled on a standardized way to control execution. There are numerous things that work, an advanced rules engine implements several, but none of them are 100% satisfactory for everyone.
One answer to these problems I see is "rules and schemes" where there are two programs that exist side-by-side, one that defines what is to be done and the other that fills in the details of how exactly it is done.
I can see something like that for the general programming language case. (Write a "style sheet" that explains how memory management is done) Also sometimes I fantasize that the way to achieve what Rust is trying to achieve is some combination of
(1) A really good macro assembler
(2) A theorem prover
(3) An ergonomic parser generator that makes writing rich DSLs easy and completely mainstream.
(1) is a good project (e.g. gas is by and for people who hate assembly language), (3) is a good project (I can rant about how bad parser generators hold developers back), the (1)-(2) punch is appealing with the the caveat that portability and optimization are problems in that case, but those could be addressed by developing architecture-specialized macro packs and (4) A general-purpose superoptimizer
which hooks into (2) which is itself a project the world needs.This is indeed the case! Rust's borrow checking is the first step towards "regions", a more general and more flexible model. TL;DR: We convey to the compiler that a certain set of objects are conceptually in the same region, and then we can turn immutable the entire region at once.
Pony and Forty2 [0] first came up with them, and Vale is building them into the language as first-class citizens and blending them with borrow-checker like semantics [1] to eliminate memory safety overhead.
It helps us do patterns that more traditional borrow checking has trouble with: observers, dependency references, delegates, callbacks, some forms of RAII, and intrusive data structures. This is mostly because regions get a lot of the borrow checker's benefits while still allowing mutable aliasing.
[1] https://verdagon.dev/blog/zero-cost-memory-safety-regions-pa...
For example, I once saw someone bring in an entire message-routing framework (Yew) because they couldn't get a simple observer to work within the borrow checker.
This is why I'm glad that Rust added Rc/RefCell; its design acknowledges that sometimes, the borrow checker gets in the way more than it helps, and it adds a more flexible alternative so we don't shoot ourselves in the foot by using the borrow checker in places where it doesn't make as much sense.
If you don't feel you need control over when data is copied, when there should be a mutex, atomic reference counting, and so on, you're probably reaching for the wrong language. IMO giving us explicit control of low level behavior is not a detriment to ergonomics as much as it is a benefit. Add in the package manager and great compiler and it feels like first class dev experience to me.
Isn't taking control away from the programmer the entire point of Rust? I thought the premise of it is that programmers can't be trusted.
That sounds like a criticism, but I don't mean it as such. It's just what I hear when I hear people talking about the value of Rust. Is my understanding incorrect?
On the other hand, I am often dissatisfied with tokio‘s incredible complexity and the fact that it‘s the accepted async solution in the ecosystem.
My take... I can see their use, but they should be confined to the outer layers of the onion.
Core components need not (should not) be written in this style.
async is just a function returning a promise.
Its convenience at the front end of the application shouldn't be allowed to cause distress at the lower levels.
The innate complexity of the ownership rules make a Pythonic Rust unlikely, someone must manage the memory so you either put up with that complexity, manually do it with malloc/free, or let the garbage collector do it (in which case it's not Rust anymore).
Perhaps you could have a Go-like Rust where everything that escapes the function or breaks ownership is automatically transformed in a reference counted object (which is still a form of garbage collection, but deterministic and compatible with system programming). So that the syntax is simple and programs are easy to compile, but you might get performance bugs when the program does heavy use of the ref count, invalidating cache lines left and right etc.
Some languages that are going this direction, including D [0] and Vale [1]. Vale's particular insight is that we can get the benefits of borrow checking with isolates (from Pony) and integrating "pure blocks" and pure functions into the type system, so to speak.
> ... breaks ownership is automatically transformed in a reference counted object ...
Some languages actually do this! Lobster [2] uses borrow-checker-like semantics and falls back on reference counting. And worth mentioning is HVM [3], which falls back to cloning.
[0] https://dlang.org/blog/2019/07/15/ownership-and-borrowing-in...
[1] https://verdagon.dev/blog/zero-cost-memory-safety-regions-pa...
As a general sentiment, I fully agree that improving developer productivity while maintaining safety, speed and ahead of time compilation & static typing are open problems, and all current languages still suck more or less.
Arc<T> is still Rust. Not ideal, but very much still Rust. I wouldn't be surprised if despite wrapping absolutely every object in Arc, Rust still were to perform better than most high-level languages at whatever given task.
Languages which have a GC may in some cases also do reference counting to reduce the load on the GC, but they need the GC because reference counting doesn't collect cycles.
It's trivial to make a cycle, then destroy all references to it - and in Rust that cycle lives forever, it can't be destroyed because each part of it has references from the rest. With a GC this gets collected, eventually, exactly when will vary which is why in the GC language destructors aren't as useful for resource clean-up as they are in languages like C++ or Rust.
let i: i32 = 1;
let &i: &i32 = &1;
let &mut i: &mut i32 = &mut 1;
let (i, &mut j): (i32, &mut i32) = (1, &mut 2);
I'm not sure how you'd recreate this symmetry without using the same symbol in both places.I get that "&mut T" means it's borrowed mutably, but doesn't that automatically mean that "&T" means it's borrowed immutably?
In the days of yore, an event called the "mutpocalypse" occurred where by (pre Rust 1.0) there was a huge discussion about potentially changing "&mut T" to "&only T" or "&uniq T" because the more precise model was one of sharing vs exclusivity, rather than immutability vs mutability. The immutability vs mutability model is still useful, it's just wrong in more circumstances. However, it does have the benefit of (IMO) being more accessible by describing borrows in terms of the most common effect: to mutate or not. I don't know which choice would have been the right one, but I am at peace with it.
"Rust Atomics and Locks" by Mara Bos has a great discussion of these points toward the beginning of her book, and specifically grounds the choice of which terminology to use in concrete and practical terms, which I really appreciated.
I bet the Rust developers never even dreamed of their language being easier to learn than C++. But it happened to be, so a lot of people go directly to it, and get the problems you are talking about. Unexpected success always causes some problems.
Yes. If you had to work in C or C++, Rust is a huge improvement. If you only know Javascript or Python, Rust seems way too finicky.
(If you had to work in assembler, C was a huge improvement.)
Rust ownership is language support for something C and C++ programmers had to think about anyway.
The real problem with Rust ownership is that backlinks are poorly supported. If you need a tree with links pointing back to the root in Rust, it's very difficult. There's Rc and Weak, but now you have to use .upgrade() on a weak link before you can use it, and it can fail. You can have all the objects owned by a Vec or HashMap, and refer to them by handle, but that's essentially manual pointer manipulation. Single-ownership with backlinks checked at compile time would be a big help for some data structures.
Edited: However, I don't see why my parent got down-voted.
Rust is great in that regard, for me at least. The stdlib is awesome, crates are awesome, powerful features like Iterators are awesome, and being confident in the code i produce is awesome. Which isn't a knock at C, but C just isn't for me.
A part of Rust that I very much appreciate is that once you write Rust code and get it to compile, there's a pretty good chance that it's going to do what you expect. As someone who is new to Rust, it's definitely no small feat to get the code to compile in the first place. But I think that's one of the main things people tend to love once they get over the initial hump of grokking all the different ways of passing variables around.
Agreed. I think the GP comment really underestimates how smooth Rust feels to Rust devs who have gotten over that hump. I've programmed in many languages and i confidently do not feel i am slower in Rust than other languages. Maybe not faster, but not slower in development speed.
But what i do get, for development speed, is the ability to solve large problems with many, many tools. I found this quite annoying in Go. In Rust, it's great. Complex problems are still complex, and Rust doesn't inherently simplify them - but it gives me the tools to come at problems in many ways. Which if you need it is invaluable.
Probably has something to do with how we conceptualize things.
What feels nice about Rust is that its typing system is tightly coupled with solutions that are impossible to use incorrectly.
My Mutex wraps my value. There is no way to access my value without correctly locking it first. I can‘t not handle all of my enum variants when matching. To get to the value of my result, I am forced to unwrap it, thereby handling a possible error.
While arriving at a compiling solution can be annoying, it feels nice to be able to trust.
There's a weird ideology or cultural attitude prevalent in Rust circles which does, indeed, involve endless gaslighting of anyone having difficulties with the language (at any level). It involves, amongst other things, insisting that the language is essentially so easy to write that any difficulties anyone has are not, in fact, difficulties, and the person claiming to experience them is not, in fact, doing so.
It's a form of group-identity narcissism I'm sure anyone will recognise as it's not unique to Rust (and seems to be something tech circles are particularly prone to, for, I suspect, demographic reasons).
My guess is this will diminish with Rust because of its fast growth in user numbers. It already seems more prevalant in some forums than others (stay away, for example, from the official Rust user forums, which are noxious).
A chainsaw is meant to saw wood. But it should still have a good usability.
Err, sorry. I meant to say hammer.
> But for people who care about language usability you can point to this post and say "they were not thinking about the user journey during the design process, how would you have designed it differently?"
People have been discussing how to make Rust usable on the rust-lang issue trackers and RFC repositories all the time that I’ve observed from the peanut gallery. Before the stable 1.0 release as well.
It’s not for a lack of trying.
* Austral is using linear types for zero-cost memory safety [0] and then allows for borrowing on top of that. Val does something similar called mutable value semantics, which is pretty interesting [3].
* Vale brings borrow checking up to the regions level [1] which gives borrow checking benefits while still allowing mutable aliasing, which makes it much more flexible and ergonomic.
* Cone uses borrow checking on top of any user-specified allocation strategy, such as single ownership, RC, GC, etc. [2]
[0] https://borretti.me/article/introducing-austral
[1] https://verdagon.dev/blog/zero-cost-memory-safety-regions-pa...
Those guarantees in anything more than a hello world application are hard to achieve. When people say "i want extremely high performance and safety but I want it to be simple and guessing what Im doing" are asking for completely contradictory things and normally what you get out is something that leaves you up the creek the moment you are not following their ideal use case.
>The only question in my mind for if this will ever happen is if the fully literate programming modality enabled by LLMs will make it a moot point.
Much like the above. It'll work fine for hello world applications. Anything beyond that it will be much harder because the complexity comes in making an application coherent both internally and with the external systems it interacts with. Which is fine. Plenty of stuff nowadays can be abstracted.
But it just joins the group of other unpleasant and ugly languages. It is what it is, and in a sense, it's following a tradition that's been around since the beginning.
The language focuses on readability first and borrow checking is an automatic compiler optimisation behind the scenes, with full type bound, constrained borrowing/move semantics being opt in as required.
There's loads of sensible ergonomics like this, for example large immutable parameters are automatically passed as pointers for you while the compiler enforces the immutability in the code, making things simple, efficient, and safe by default, with less cognative overhead or need for these kinds of micro-optimisations leaking into the architecture.
Saying that, Rust‘s multithreading story is better for now as it currently offers wider aliasing protection although arguably at the cost of developer friction.
Or how the Chapel language for HPC is going at it,
Rust gets the unique mix of safety and performance by making you have to deal with memory, that is fundamentally more complicated.
I am the person who hates C/C++ and likes languages like Ruby. I like Rust specifically for the reason that I don't have to learn C++ like "grown ups" and can write my crypto libraries in something much more ergonomic.
When I started writing in Rust, it was 2018 and there was old borrow checker (NLL was experimental) and error messages were much more annoying than today. And still, that was nice language that is easy to write and read once you understand a couple of basic rules.
Here are the rules that you need to learn and always keep in mind, even if Rust had a more verbose syntax. And I bet many people struggling with Rust simply were not lucky enough to have those rules explained to them.
Rule 1. By default, in Rust things are "owned" and "moved", all the time. When you do `x = y`, you literally move "y" to "x". In other popular languages you might expect automatic copying or automatic referencing, but in Rust you get an unusual "move" semantics.
This rule applies universally to all things: be it simple numbers or structs, or references, or weird Rc<T> things or whatever. Once you move "x" to another location, you cannot use it any longer from the old location.
Rule 2. As an optimization, some simple types are marked "Copy" which means that you get a cheap implicit copy whenever you want to continue to use moved value. This applies mostly to numbers and fixed-sized types. This liberates you from explicitly calling ".clone()" on stupid integers.
Rule 3. There are references, mutable and immutable, that let you avoid moving value when you don't need to. At any point of time, each value may have N immutable references or 1 mutable one.
There are lexical references (most commonly used): & and &mut, for these the rule 3 is statically checked at compile-time. And there are runtime counterparts that implement rule 3 in runtime: Cell/RefCell.
So when you design an API or use an API, you should really think about ownership of the values that you pass in according to these 3 rules. You may have these questions and use the rules above to answer them.
- Should that API "consume" (get the value "moved into") that value, or should it have read-only or mutable access to it?
- What part of code (which other value) actually owns the value and is responsible for cleaning it up?
- Is that a dumb value that can be Copy-ied explicitly, or is there non-trivial copying cost that requires explicit references or clones for it?
- What does it mean to say `y = &x`? Per rule 1 we move reference "&x" to "y", but since it's a non-mutable reference, we can have a lot of them, so it implements Copy and &x can be used again per rule 2.
There was a great post the other day about the "Register of rust", and getting to know all the different variants of these features to be proficient and being able to build whatever you want.
The same goes for async features as well. Async especially requires that you understand lambdas, borrow checking and so on. As it can be quite tricky to send a value to a tokio::task::spawn!(...) if you don't have some mastery over the borrow checker.
When you get to taking lambda in a func, that should be async then you begin to get into the weeds of rust, and where some of the nasty compilers errors show up, some of the unhelpful variants, where you are expected to know the intricacies of how lifetimes work, and how rust handles generics vs impl vs enums etc.
In the beginning I just recommend using a good old Arc<Mutex<...>> if you need to pass stuff to functions, you can still shoot yourself in the foot, but you can take the optimizations piecemeal.
In programming you might use different ‘registers’ in different parts of a program, but for all of the lower teachings about ‘encapsulation’, ‘information hiding’, and such programs as a whole have to have certain global invariants respected if they are going to work correctly…. Particularly when it comes to memory management!
Garbage collection is a great facilitator for encapsulation because it means you can just allocate and not think at all about deallocation. A strength of C is that each program can implement a custom optimal memory handling strategy but that’s a roadblock to reuse with libraries because any library has to adapt to the memory allocation strategy of the program as a whole.
Superficially it looks as if objects, inheritance, and polymorphism are the key features for code reuse in Java but I’d make the case that the garbage collector is more fundamental - you certainly lose some performance but neither C nor Rust has managed the feat that LISP and Java has of encapsulating memory management in a way that allows arbitrary code to work in the same runtime together.
That's so deeply ingrained into my mind that I really struggle to interpret it differently.
Those subtle distinctions were the overwhelming force leading me to ampersand driven development in the early days, i.e I had the "pointer" mental model and tried to shoehorn that into Rust somehow and get that pointer to work like it does in C.
I don't think I saw a simple write-up with clear examples of what to do and what not aimed for beginners, seasoned rusters just act like slick professionals that wouldn't make such nonsensical silly mistakes and beginners are to somehow emulate their genius.
It's especially helpful to people who are both new to Rust AND come at Rust from language ecosystems with a garbage collector.
People are new to Rust but have come to it from a C/C++ have had to worry about ownership all the time, so they might not find anything here a revelation except this: "Oh wow, the Rust compiler takes care of all of this for me! No inadvertent memory leaks?! Yaay!"
> It's especially helpful to people who are both new to Rust AND come at Rust from language ecosystems with a garbage collector.
This is exactly the audience I was writing for so I'm very happy that you thought so.
It seems the latter is more common than the former, and that would avoid to have to add "&" everywhere.
Currently the types are:
owned T T
ref of T &T
ref of ref of T &&T
You're suggesting that instead you skip the "&" and write some sigil for owned types, say "@": owned T @T
ref of T T
ref of ref of T ???
How do you write the type "ref of ref of T"?On its own this isn't a super compelling argument, because "&&T" is an unusual type that one doesn't normally use. But it hints at the fact that "&" is a modifier. The stronger but less pithy version of this argument is that if you have a type parameter "T" it's essential that it can be instantiated as "T=&U" for some "U".
EDIT: come to think of it, you don't often write "&&T", but it is commonly used. If you `println!("{}", x)` where "x" is a reference, the "println!" macro also takes a reference and you get a "&&" type.
Yup, i see them all the time in iterators too. Eg `foos.iter().filter(|t| ..` `t` is `&&Foo` in that example, iirc. Not that you usually see it though, due to closures obscuring types.
I have to assume rust creators knew what they were doing since they are obviously way more experienced at this than me, but I still don't get it.
- Does "i32" mean an integer or a reference to an integer? You almost always want it to be an integer, so maybe we carve out an exception for small primitive types, that they don't get an implicit "&".
- Likewise some library-defined types like "Rc<T>". "Rc<T>" is the way you store a ref-counted T. So you usually want "Rc<T>" instead of "&Rc<T>". Is there an exception for this type, too, or do you always have to write "@Rc<T>"? It's defined in the standard library, so if it gets an exception than there has to be a language mechanism for "types that should not have an implicit &".
- The ".next()" method on iterators has the type signature "next(&mut self) -> Option<T>", where "T" is the type of the iterator's elements. Under your proposal, you'd write "next(&mut self) -> Option<@T>". If "T=&str", then you're returning an "Option<@&str>". Which has to be equal to "Option<&str>" or else everything breaks, but that might not be super intuitive to programmers.
That last one's the most important, though I don't know how to explain it clearly. If you have a type parameter "T", then "T" does not mean owned T. It means "T", whatever "T" is. If "T" is a reference, then it's a reference. And if you have a type parameter "T" then "&T" means a reference to "T" whatever "T" is. If "T" is itself a reference, then "&T" is a reference to a reference.
There's one other thing in Rust that would be kind of difficult if passing a reference were the default, rather than the owned value. Rust has implicit returns so the last thing at the end of a block or function is returned. If you needed to explicitly ask for ownership, you'd need to do that at the end of every function. Also, Rust will yell at you if you try to have a function return a reference to a value that's going to be dropped.
In C++, I think that the use of '&' came from the use of '&' in C as meaning "the address of". A reference and an address to a value are similar concepts.
It was tedious and eventually dropped. For example, it's more natural to move in assignment. `= move` is weirdly boilerplatey, `=` borrowing is unhelpful, and `=` moving without the move keyword is inconsistent.
Also the moment something is borrowed starts a lifetime scope, which is useful to know. It'd be harder to notice loan scopes of loans were implicit.
f(&s);
is practically equal to let r = s.borrow();
f(r);Basically: even though I know exactly what the ownership does in the context of "it's a clever C" I'm still tripping over myself when I take the same concepts to be "a clever C++".
For those of us who are allergic to JavaScript.
And it's this that can quickly get you into trouble with excessive & and &mut references where you don't need them, and trouble with borrowing generally. Passing that &self argument around all over the place -- even when you might not need to -- means you end up borrowing or declaring mutability at times when you may not want to. Also leading down the path of ending up resorting to Arc/Rc, or Box etc.
It's one thing I struggled with, moving mostly from C++, but I suspect people coming from a C (not C++) programming background struggle with a lot less as they are used to what I'd call module-function-level programming, rather than binding functions to classes all over the place.
The balloon one is a bit busy and I didn't find it to have much explanatory value in that context.
Update: also made them smaller.
Edit: Aside from that, as a Rust neophyte I did like the content.
I personally appreciate the content, so thanks for that!
Yes, bike shedding. People love to bring that up as a way to deflect criticism they disagree with.
Is it that you used a child sharing their toy as a way to explain the concept, and you needed to remind us what a toy was?
They are also somewhat inconsistent as to where they appear.
You can remove all but one or two, and the article won't be any worse :)
&mut var
Instead of
mut &var
Having two version of mut just doesn’t make sense to me. I love rust, but haven’t gotten nearly enough time to use it, and little things like this use up more memory in my brain than it should for such a well thought out system.
An argument could be made that it shouldn't have been '&mut' and instead be something like '&exclusive'.
(or links to such examples)