A half-hour to learn Rust
fasterthanli.me
fasterthanli.me
I'm curious what other what other developers who primarily use Python think of this article and Rust in general?
Edit - actually I was probably thinking of this podcast with the same interviewee: https://rustacean-station.org/episode/004-rust-in-production...
This has been my, and a lot of my colleagues', experience with Rust. Never have I seen people fall in love with a programming language so strongly. And the love lasts for a long time.
That may not be what you meant but it seems like that’s what people are understanding.
This suggests experience far more than a single hour, does it not?
They didn't, though? They indicated that they had a similar experience of falling in love with it quickly. That says nothing about when that experience happened.
All those lifetime annotations are not sheer beauty or pretty, sure they are necessary but not nice to look at if you are comparing it to a higher level language.
Eg cloning a string leads to an extra allocation and a memcopy.
If you want to get a similar performance profile to GC languages, you have to stick your types behind a `Rc<T>>/Arc<T>` or `Rc<RefCell<T>> / Arc<Mutex<T>>` if you need mutability.
But modern allocators hold up pretty well to a GC, which amortizes the allocations. The extra memcopying can be less detrimental than one might think.
const obj1 = { a: 32, b: 42 };
function foo(ref) { ref.a = 0; }
foo(obj1);
console.log(obj1);
in JavaScript, one is just using the variable name as a "holder" of some value. One doesn't have to designate that that variable is being passed by reference. If one wanted to actually copy that object, they'd have to devise a mechanism to do so. In Rust, if someone doesn't specify, using the & symbol, that something is a reference, it'll end up moving the value.Basically all I was saying is one can not approach writing Rust with a Java/JavaScript mindset. (That a variable is just a bucket holding a value). Care needs to be taken when referencing a variable as it may need to be moved, copied/cloned or referenced. In the case of copying, another memory allocation is done. So if someone approaches Rust from the standpoint of "this word represents a value, and I'm going to use it all over the place", they can find themselves blindly allocating memory.
Often you don't need to care about the extra allocations and can just deserialize to owned types.
The code for owned deserialization certainly ends up looking more elegant.
I want to say that seems like a valid concern but in practice I've seen it come up only rarely.
However when you take a high level feature like overriding operators which can be done elegantly in Python, for a complied language, Rust's way is quite concise, readable and to my eyes quite pretty.
Edit: Typos
You don't have to do it, but if you want to do it, being able to do so in a way that's verified and enforced by the toolchain beats doing so in a documentation comment.
Now every time I read a doc string saying that I need to "deepcopy" something in Python for some API usage pattern to work properly I cringe.
With a checker you're forced to think: do I really want to pass a copy/clone of this? Or do I want to let that function borrow it? Or borrow it mutably?
Assume you had some code that takes a file name and calls open on it. One day you decide you want to print that filename before you open it. Naive code will cause the name to “move” to print and unusable to the open in next line. Even though it is perfectly understood by all parties that there is no threading involved and print would finish before the next use of that string. Yes, I can create a borrow or clone, but having to think of it every single line of code even when there is only one thread of execution is really painful
Edit: I get print is a macro, but imagine a detailed logger for this case.
Here, if I have a `&T` and I try to call a function that has a `&mut T`, the compiler will tell me that's not gonna work - and then I can pick whether I want my function to take a `&mut T`, or if I want to make a clone and modify that, etc.
There's a learning curve, it's a set of habits to adopt, but once you embrace it it's really hard to go back to languages that don't have it! (See the rest of the comments for testimonials)
Bignum arithmetic is an example of the latter. You want to just work with numbers, and in Python you can, but in Rust you must clutter your code with lifetimes and borrows and clones.
Swift's plan to allow gradual, opt-in lifetime annotations seems really interesting, if it works.
let a = Integer::from(10);
let b = a + a; let b = &a + &a;
will work, but I agree it's unfortunate that this is necessary.GC protects you against double-free and use-after-free, but memory leaks? Nope.
Foo* foo = new Foo();
...code that uses foo...
This is a memory leak in a non-GC language, but not in a GC language.In a practical sense... is it your personal experience that memory leaks are equally prevalent in GC and non-GC languages? I've spent decades working in each (primarily C++ and Java, but also Pascal, C, C#, Smalltalk...) and my experience is that memory leaks were a _much_ bigger issue, in practice, in the non-GC languages.
It is my experience that when people work with GC languages, they treat the GC as a blackbox (which it is) and simply won't bother investigating: do they have memory leaks? Of course not, they are using a GC after all, all memory-related problems solved, right? Right... With code that relies on free(), I can use a debugger and check which free() calls are hit for which pointers. Even better, I may use an arena allocator where appropriate and don't bother with free() at all. With a GC I'm just looking at some vague heap graph. Am I leaking memory? Who knows... "Do those numbers look right to you?"
Memory management issues are usually symptoms of architectural issues. A GC won't fix your architecture, but it will make your memory management issues less visible.
It is my experience that most memory problems in C come from out-of-bounds writes (which includes a lot more than just array access), not from anything related to free(). A GC doesn't help here.
> In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in a way that memory which is no longer needed is not released.
In most of your scenarios, e.g. "pushed to some queue", the object in question is still needed. Hence, this is not a leak. Presumably, the entry will eventually be removed from the queue, and GC will then reclaim the object.
At any rate, I think we're moving past the point of productive discussion. My experience in practice is that memory leaks are more common / harder to avoid in non-GC languages. Of course a true memory leak (per the definition above) is possible in a GC language, but I just don't see it much in practice. Perhaps your experience is different.
If I have a queue with elements and I won’t be accessing some of it in the next part of the program, is it a leak? Also, remember that certain GCd languages intern strings, is it a memory leak since it will not necessarily use it anymore?
To provide an example for a different case: programs written in Gallina have the weak normalization property, implying that they always terminate.
With a "proper" GC engine, anything that is no longer able to be referenced can be safely collected. Barring bugs in the GC, none of those can leak. But, you can unintentionally keep references to things for a lot longer (possibly unlimited longer) than you need to. Which looks like a memory leak, but is actually unintentional liveness.
And to prove the difference between "cannot be referenced" (a property that can in principle be checked by consulting a snapshot of RAM at an instant in time) and "will not be referenced" (a larger set, we will never reference things that cannot be referenced, but we may not reference things that are reachable, depending on code) feels like it is requiring solving the halting problem.
And for free()-related problems, I've definitely seen code crash with use-after-free (and double-free).
Both situations prevent you from reusing memory previously used by other objects, which isn't being utilized for anything useful at that point. The distinction is valid formally, but from a practical point of view sounds rather academic.
> And to prove the difference between "cannot be referenced" (a property that can in principle be checked by consulting a snapshot of RAM at an instant in time) and "will not be referenced" (a larger set, we will never reference things that cannot be referenced, but we may not reference things that are reachable, depending on code) feels like it is requiring solving the halting problem.
As usual, looking for a general solution to such a problem is probably a fool's errand. It's much easier to write code simple enough that it's obvious where things are referenced. Rust's lifetime semantics help with that (if your code isn't all that simple, it will be apparent in the overload of punctuation). If not Rust, then at least it would be good if you could check liveness of an object in a debugger. In C you can check whether a particular allocation was undone by a free() or equivalent. I'm not aware of any debugger for e.g. Java which would let me point at a variable and ask it to notify me when it's garbage collected, but it sounds like something that shouldn't be too hard to do, if the debugger is integrated with the compiler.
Sarcasm?
Some syntax is close to Python so some mental load is minimized, i.e use of snake_case, self, None and type annotation syntax, dict unpacking.
Some lines read like sentences i.e. for loops, single line if statements, impl Foo for Bar etc. Some design choices also read better I think, for example, let reads better than var.
Of course such preferences are personal. I've read other comments that mention that the tutorial covers only basic Rust features and it can get much more complicated when using more advanced features.
Edit: Added sentence about advanced features.
In other words, someone who doesn't have a CS background, never took theory of programming languages, etc. "Python programmer" is like the 2020's equivalent of a "HTML developer" from the 2000s.
Also reading Python code is easier (less syntax noise) on the eyes. The article above is very beginner Rust, and I won't rely on that to look at actual Rust code in the wild.
If you want to take a look at what actual Rust code in the wild, take for example, a web server Actix, and try to figure out what the documentation says.
I don't agree with this, and, if anything, this reads very biased.
Insofar, Rust has made my life a lot easier, and I have not run into any major issues aside the borrow checker. And this was early on. Two years now playing with the language and I barely run into it anymore.
Majority of people will probably want to use Rust for web? Which makes async needs to be ergonomic enough if it wants consider wide adoption.
At least idiomatic Python shuns wildcard imports that obfuscate where symbols are coming from (that drove me insane in Ruby).
On the other hand Rust code tends to be very strict about what your types are (even more so than a language like C++ where metaprogramming is duck-typed by default). It can lead to complicated code, but baring some weird operator overloading decision you should know exactly what calls what from whom when you look at any method or function.
Rust code can be tricky to write at times, but I generally find it a pleasure to read. Sure, ultra-complicated generic code can be overwhelming, but this complexity would be here in one form or the other regardless of the language, Rust just forces you to be explicit about it.
Disagree here. Like article Rust 2018 is very nice and ergonomic. Iterators, Lifetime Elision etc are nice to work.
Regarding noise many people consider those noise but I find noises like return types etc very useful. Because I can be sure the return type. Regarding actual code actix doesn't look that bad from examples also.
I use warp and its pleasant to work. The only thing I hate is compilation time other than that I don't think I have any major criticism against rust. But compilation time is near to cpp etc so ...
let re = Regex::new("(?P<min>[0-9]+)-(?P<max>[0-9]+) (?P<letter>[a-z]): (?P<password>[a-z]*)").unwrap();
re.captures_iter(&contents).map(|caps|
Input {
password: caps.name("password").unwrap().as_str().to_string(),
letter: caps.name("letter").unwrap().as_str().chars().next().unwrap(),
min: caps.name("min").unwrap().as_str().parse().unwrap(),
max: caps.name("max").unwrap().as_str().parse().unwrap()
}
).collect()If the code is supposed to be maintainable, you could also make something like a FromRegex trait for Input. It would be a good idea to try exercism's mentoring thing to get better at writing it the easier way the first time. The mentoring thing really is what helped me to think in ways that made this mess easier to avoid.
The really horrendous scenario was when I was trying to navigate pest iterators for parsing according to a grammar.
error[E0599]: no method named `parse` found for enum `Option<regex::Match<'_>>` in the current scope
--> src\main.rs:24:39
|
24 | min: caps.name("min").parse().unwrap(),
| ^^^^^ method not found in `Option<regex::Match<'_>>`I don't know what the structure Input looks like but I played around with your code and it seems to work with as_str()
https://play.rust-lang.org/?version=stable&mode=debug&editio...
That said...both languages read like close siblings to me to the point I find it annoying switching between the two because I keep trying to use each ones language semantics in the other subconsciously.
There's a bit of a progression with Rust, where at first you see the examples and you go "this language is so beautiful!" Then you try to write something nontrivial in Rust and you go "wow the compiler will NOT stop yelling at me, how does anyone write anything in this language?" Rust has a fairly austere learning curve in general, and it takes some getting used to.
That passes, though, and then you really do get to experience the elegance and power which sold you on Rust in the first place. There's a period where writing Rust feels substantially slower that writing in anything else, but that passes too.
It really is as good as it sounds, but it might take a while before you're accustomed enough to Rust's paradigm that it feels that way.
For any project where performance or correctness are significant concerns I'd much rather use Rust than Python. It provides a lot more tools to help you write correct code, and express invariants in a machine-checkable way. This means that they are maintained when the code changes, even when multiple contributors are involved. I'm must more confident in my ability to ship correct code in Rust and maintain that correctness over time.
Rust also doesn't have the performance ceiling (floor?) of Python, either for single threaded programs, or — especially — for those that benefit from concurrency or parallelism. Of course for some progames there's a clear hot loop that you could implement as a native extension in Python, but other workloads have relatively flat profiles where the performance bottlenecks are making allocations or similar.
As well as the actual language features, the commitment to backward compatibility from the Rust authors means that you don't get regular breakage simply from updating to a newer version of the language. I think Python 2 being 2.7 for such a long time gave people a false impression of how stable a foundation Python provides and the fact that point releases of 3.x often cause problems feels like it causes a lot of unnecessary makework for Pyton users and is rather offputting.
That doesn't mean I'd always choose Rust of course. You do require more upfront design to get something that works at all. Some projects also benefit greatly from not requiring a compile step and making use of the ubiquity of a Python interpreter. And I think I'd find it difficult to justify using Rust for a typical web backend that's mostly composing together various well-tested libraries to provide an API on top of a database.
It was a rough transition, to be sure. Python2 was released 20 years ago, and Python3 12 years ago. It is a pretty stable language.
They manage this by allowing using a different epoch in a library than the application that uses it, and defaulting to the original epoch if you don't ask to use a new one.
The vast majority of rust 1.0 libraries should still work with modern rust programs, I vaguely recall that there was one minor backwards incompatible change as of a result of memory safety bug (an exception to the guarantee), but I can't remember what it was and I can't find it with google so it might actually be all rust 1.0 libraries still work.
The fix for https://bugs.python.org/issue40870 caused me some grief when upgrading from 3.8.3 to 3.8.4 (though to be fair, the ast module has different stability guarantees).
The argument is that being on 2.7 for so long gave a false impression of the language being more stable than it is - developers just weren't using new versions.
So 2020 rolled around and the pypi libraries they were using were no longer supported even though RHEL would support python 2.7. So yeah, it was a really bad experience for everyone involved.
Any reason for why Rust over Ada/SPARK?
Due to lifetimes it's easy to keep string slices as references into the original memory and if you do need to modify some strings, you can use CoW.
The way Rust deals with encoding also makes it much safer to use Rust. Since you need to be very explicit about which encoding you convert to what and if you want to allow lossy conversions.
I don't think there is much of an equivalent in ADA for this. ADA has other benefits, like the delta (fixed point) types which help a lot in embedded projects.
That said, Rust seems to have reasonably good performance compared to C/C++. Also the concept of lifetimes is interesting too.
Just because your program compiles in C++/Ada(no-spark)/C/Java/Rust doesn't mean it's correct. If it compiles in Rust, the compiler is telling you it's memory safe and thread safe.
At some point I just started writing these things in Rust instead. Describe what I want deserialized as a struct. List the fields I want as enum variants. What's that, rustc, the "name" field is optional? Ok, that makes sense, I'll handle this right away. Done. Hey, rustc, how come people talk about fighting you all the time when you're actually the world's greatest pair programmer?
Semi-colons do make make possible multiple statements on a single line -- but surely there's a stronger rationale than that.
I've heard this many times before, but as the guide[1] says:
"You might encounter it in two situations... Both are related but subtly different and this is a common source for confusion when learning Rust."
'static means different things for references and trait objects.
ie.
'a: 'static --> reference with lifetime 'a lives forever and can never be dropped.
T: 'static --> Type T has no references in it; it is effectively 'entirely owned' by the owner of an instance of T.
These are totally different things with the same name.
(I believe technically there are actually three; `<T: 'static >` is a type constraint and `T + 'static` is a trait bound, but that both mean the same thing as far as I know)
[1] - https://doc.rust-lang.org/rust-by-example/scope/lifetime/sta...
Lifetime: lifetime means that the first lifetime outlives (is as long or longer) the second
Type: lifetime means that the type is constrained by the lifetime. Because 'static means "the lifetime of the whole process". That means that the type is not constrained.
T: ‘a is T outlives ‘a; but types are not generated at runtime.
All types are static; which is to say they are created at compile time and exist for the lifetime of the program.
Or does rust generate type variants on the fly at runtime?
I didn’t think it did...
It is a constraint applied to arguments at compile time... but r, that’s what I thought anyway.
Yes, that’s true, but you can make it a bit more specific by saying “all the references in T outlive ‘a”. Then it should make more sense, as references are generated at runtime.
This gets to the heart of what makes Rust an interesting language, as references are generated at runtime, but how long those references are valid for is checked at compile time using lifetime bounds.
T<'a> and T<'b> are different types altogether (although, being generic, they can resolve to the same type if 'a == 'b, but it's not required). All this happens at compile time.
When you say T: 'a you say that T is a subtype of 'a hence it lives longer.
https://doc.rust-lang.org/nomicon/subtyping.html
Maybe you're being confused by misconception 1 here?
https://github.com/pretzelhammer/rust-blog/blob/master/posts...
Type T, being generic, can be an OwnedStruct, but also an &'a BorrowedStruct or a StructWithReferences<'a>. The owned one is a subtype of 'static since it's owned, but the ones with lifetimes are subtypes of 'a which itself (being a generic lifetime) can be a subtype of 'static or any other lifetime. Again, all this happens and is checked at compile time. This ensures that at runtime, the actual references are alive as per their lifetimes without explicitly checking them anymore.
T: 'static does not mean the references in T must exist for the lifetime of the application.
Ie. the lifetime constraint on T isn’t the same 'static from &'static where the reference must life for the entire lifetime of the application.
Types are static. T: 'static applies to instances at runtime.
These instances do not have and are not related to the 'static lifetime which is “the entire length of the application”.
I accept:
> Type: lifetime means that the type is constrained by the lifetime.
I don't accept the explanation:
> Because 'static means "the lifetime of the whole process". That means that the type is not constrained.
A does not follow from B.
If you want something to mean "A type cannot have references in it" then invent a 'noref lifetime.
'static in this context would mean that all members of T must be 'static, which means that all instances of T must be 'static.
It does not mean that.
I don’t understand why they have the same name; they are not the same thing; it is an example of failure to have orthogonality in the language design in my opinion.
Check misconception 2 here, I think it addresses your point.
https://github.com/pretzelhammer/rust-blog/blob/master/posts...
EDIT to your edit:
> 'static in this context would mean that all instances of T must be 'static.
You mean in T: 'static?
No. It means that any instance passed as type T must be bound by 'static and therefore could be held up to the end of 'static. This does not mean that they're allocated at compile time, it just so happens that static variables (allocated at compile time) are 'static but the causality is reversed.
> If you want something to mean "A type cannot have references in it" then invent a 'noref lifetime.
It can have references in it! As long as they're bound by 'static.
Here's an example: https://play.rust-lang.org/?version=stable&mode=debug&editio...
I just maintain that the word 'static is being overloaded here to mean multiple different things.
'static is not the "lifetime of the entire application" when it is used in the context of T: 'static.
> It can have references in it! As long as they're bound by 'static.
:)
...but it can also have values in it which are not 'static.
So is T: 'static, or not?
It's arbitrary semantics; ...but my take on it is:
- IF you take "x is 'static" as meaning the "X is valid for entire lifetime of the application"
then if:
- x: &'static 'is static' and must be valid for the entire lifetime of the application.
I would expect:
- x: T + 'static 'is static' and must be valid for the entire lifetime of the application.
I'm happy to agree that's not what it does mean, what I'm saying is that it is inconsistent for it not to mean that.
I don't think that's right. It can only have references which live at least as long as 'static does (or longer, but 'static is the longest so...)
Yes it is.
T: 'static means T can live up to the end of the "lifetime of the entire application".
> ...but it can also have values in it which are not 'static.
I don't follow. Values are indeed bound by 'static. If they weren't we wouldn't be able to pass values to other threads (which can potentially last as long as our application's main thread).
> 'static is not the "lifetime of the entire application" when it is used in the context of T: 'static.
It is. Any owned instance without non-'static references inside can live up to the "lifetime of the entire application". You might drop them earlier if you wanted to, but you don't have to since it can live up to the "lifetime of the entire application" and therefore can be passed for example into a thread that can hold the value up to the end of the "lifetime of the entire application".
Any owned value can be held indefinitely as long as the program is running.
I'm taking a guess here: you mean that values' lifetimes can be constrained (I guess you mean by dropping the actual value). But it's the owner the one that ended it earlier, not the caller (where 'static applied). You will never be able to have an owned value with a lifetime shorter than 'static without dropping it and, if you drop it, you cannot pass it anywhere. Hence why any owned type that is passed is, by definition, bound by 'static.
> ...but my take on it is:
> - IF you take "x is 'static" as meaning the "X is valid for entire lifetime of the application"
> then if:
> - x: &'static 'is static' and must be valid for the entire lifetime of the application.
> I would expect:
> - x: T + 'static 'is static' and must be valid for the entire lifetime of the application.
Your expectations are correct and that's what it is. Just replace "must be valid" with "can live up to".
That's why you need to pass T: 'static to threads, because a separate thread needs something to hold up to the end of the application since a thread can potentially never end.
'a: 'static is read "'a outlives 'static" [1]
T: 'static is read "T is bounded by 'static" (apparently, although I can't find a reference to it).
The syntax is the same, the meaning is different.
Maybe the 'static part of these two things is the same, but they seem to me to:
- mean different things
- use the same syntax
It is what it is I guess... just confusing as to why it was decided to use the same syntax for these things, instead of something different.
You could argue that adding new syntax makes the language more complicated; but I'm not sure. Does it make it less complicated when you overload the same syntax with multiple different contextual meanings?
Opinions probably vary.
[1] - https://doc.rust-lang.org/reference/trait-bounds.html#lifeti...
T: 'static would happily typecheck with &'a str if 'a: 'static.
T: 'static typechecks:
- OwnedValue
- OwnedValueWithReferences<'a> where 'a: 'static
- &'a ReferencedValue where 'a: 'static /// &'static ReferencedValue
- Foo<&'a Bar> where 'a: 'static /// Foo<&'static Bar>
...and more.
See the example here: https://play.rust-lang.org/?version=stable&mode=debug&editio...
Notice how bar2 has a &'a str where 'a: 'static and it can be happily passed to bar.
Of course in T: 'static you're subtyping a type and in 'a: 'static you're subtyping a lifetime (which implicitly subtypes the type that it's applied on)... but the ": 'static" part means exactly the same: "the left part of this bound can live up to the end of the application". Whether it's a lifetime, a borrowed type or an owned type does not matter.
> It is what it is I guess... just confusing as to why it was decided to use the same syntax for these things, instead of something different.
Because they are the same.
We could of course separate them into 'noref, 'yesrefbutstatic, 'staticref, etc. But then we'd have a needlessly restrictive std:.thread::spawn that would accept only Owned, or only Owned<'static> or only &'static Referenced. The implications are the same, hence they're the same. We wouldn't gain anything and we'd be needlessly restricted.
A simpler way to put it: owned values have an implicit 'static lifetime.
If "the left part of this bound can live up to the end of the application" then why is &a not 'a where 'a: 'static? a can live up to the end of the application. &a can live up to the end of the application.
Why is the result "argument requires that `a` is borrowed for `'static`"
fn foo<'a: 'static>(a: &'a str) { println!("{}", a) }
pub fn main() {
let a = "hello world".to_string();
foo(&a);
}
So I guess I'm going to have to just agree to disagree on this one and bow out of this conversation thread I'm afraid.[1] -- https://play.rust-lang.org/?version=stable&mode=debug&editio...
If you do 'a: 'static, then you just said 'a is at least as long as 'static.
When you borrow the String, you just created a lifetime that is not as long as 'static. Variables are dropped (and hence unborrowed) in reverse order. So 'a will necessarily be dropped before its owner, hence it's shorter than 'static.
As you can see it complains that it's dropped at the end of main() even though it should be borrowed for 'static. If this was an owned value it would NOT be dropped at main() since it would be moved into the function on call.
Nothing surprising here.
> &a can live up to the end of the application
Nope. Imagine spawning a thread and passing &a but keeping 'a' in your main thread.
> bow out of this conversation thread I'm afraid
Welp I did what I could.
Nope, a reference to a stack frame can't live up to the end of the application. The stack frame gets deallocated and the referent ceases to exist; therefore the reference you're creating in your linked example doesn't outlive 'static. `main` is not an exception to this in Rust.
It means that T does not have non static references, so it is not a requirement that it lives for the lifetime of the application but can do so.
> 'static in this context would mean that all members of T must be 'static, which means that all instances of T must be 'static.
Your "which means that" isn't true. It doesn't mean that. The syntax type : lifetime indicates that the values of the type MUST BE ABLE to outlive the lifetime. It doesn't mean that they NEED to outlive the lifetime.
This means, for example, i32 : 'static even in the case doesn't live the whole 'static lifetime. It COULD live, though, if the author of the code allocated it statically.
Another way to think about it is that “T: ‘static” restricts all references in T to be static, in the same way that “‘a: ‘static” restricts ‘a to ‘static. The case when T doesn’t contain any references is then just a boring base case.
So neither `&'a i32` nor `MutexGuard<'a, i32>` are 'static (unless 'a is), because you shouldn't keep references like that around longer than the stuff it points to. But i32 by itself satisfies i32: 'static, because it's perfectly fine to keep an i32 around forever. (But that doesn't mean that every i32 will stick around forever.)
So `T: 'static` doesn't require types to live for the entire duration of the program. It requires borrows if there are any to be valid for that long. If there are no borrows involved, then 'static is ignored.
In practice `T: 'static` should be understood as "all temporary references are forbidden here".
So, IMO: not better than the Rust book. It gives a first glance of Rust, something to accustom the eyes to a different syntax, but sidesteps the difficult bits, which can make transitioning so frustrating.
No substiture for the book, though.
Some love that style (the detours, the stream of consciousness) and some can't stand it. The Rust book is excellent, and a completely different style — they're complementary!
Disclaimer: am the author of Rust in Action
Did a free course in December with him, and I'm still watching the classes because it has so much great info there.
Also I do recommend the Rust Programming, it really teaches you "how/why" use Rust.
To conclude, rust-learning (at GitHub) have great links, amazing articles about parts of the language, there is so much knowledge there, just go collect it :P
He previously said “That's too hard for an introductory book and not detailed enough for a reference manual.” It is very difficult to get this right, given our goals, and so reasonable people may think we fall short there.
They are suited for developers who already have some experience in another language, and they last from 45 minutes to 2 1/2 hours.
maybe the site's reading time estimator is broken? sarcasm intended.
But seriously, it is good to have people writing things like this.
Another thing few people realize is that the "incremental" compilation mode that's the default for debug builds can also be enabled for release builds!
In CI, something like sccache can help a lot (using the GCS or S3 backend). It makes GitHub Actions' two-core limit almost bearable. Almost.
All of them are. I first started disliking Medium for just that reason.
I'm confident that this does not only apply to programmers :)
No, it's just made for prose, not tutorials.
It was not rewritten in rust?
https://gist.github.com/ityonemo/769532c2017ed9143f3571e5ac1...
The article also skims over the single ownership model which is a big difference with Rust. And it does miss about creating macros, cells, threading & mutexes, heap allocated types, unsafe code, Rc, std::mem, and the whole crates and cargo ecosystem. Which is why I think this should have been titled "half-hour introduction to Rust syntax". Hopefully this does bring more people on the Rust train. I think 2021 will be a good year for Rust :)
If you have more, do engage in a joust^W friendly collaboration with the compiler, which will get you quite far since diagnostics are a first-class feature :)
I must be slow, being an old fart... I've been at it for 53 minutes and got about 1/2 way before all the questions in my brain stacked up to "full".
I'd add a recommendation at the top of this to have a Rust compiler handy.
{} were called braces when I learned programming, [] were brackets... this tripped me up, Unicode calls these {} curly brackets ?!? (Why did it trip me up? Because on my screen in non-dark mode, { and [ look identical due to my eyesight, and I assumed I was looking at [ because the text said that's what it was... as you get older, you'll understand)
I don't understand why b=a; c=a; <-- doesn't work because a is "used up"???
I'll get a Rust compiler and start again.
I'm allergic to "macros" as they have had a special place in hell because of their misuse in C... I hope Rust is more sane.
Regarding references, the compiler does flow analysis and tries to enforce a sort of static rwlock semantic on variable level. You either have a single mutable reference xor N readable references to the same variable.
If b is a mutable reference to a, c cannot point to a until b reliquishes the "lock", which happens when b goes out of scope.
You know how C has a problem with aliases? (multiple variables referencing the same thing)? Which introduce bugs, prevent optimizations, etc?
Well, Rust tries to prevent this, and make more explicit (and known to the compiler) when you do this...
I just googled it... why the heck would you copy pointers? That's insane!
In my example, a, b, and c were variables, not pointers.
At least in my book pointers are still variables (as in "a pointer variable"), and a variable is any named value, whether it's a scalar or a pointer or a nth-pointer, or what its storage is.
But you mean that in your example there is no way to affect the previous value, right?
>I just googled it... why the heck would you copy pointers? That's insane!
Well, copying values and passing them around would be too costly on memory (for larger structs especially), and would prohibit several techniques.
Pointers are used reference things allocated from the heap, and never anything else, unless you're insane. Pointers get directly handled in linked lists, trees, etc.
If at all possible, pointers should be avoided otherwise.
Values passed to a procedure can be done by value (the default in Pascal), or by reference (VAR parameters).
I don't see why anyone wouldn't copy values by default... it is the only sane way to do things.
Variables by themselves are not much. They inherit the properties of the type they are bound to. So what you can do with them can be as restrictive or as permissive as the type allows. That type can be a pointer/reference as well.
People routinely use pointers to things on the stack in several languages. Rust even makes it safe to do that, using lifetimes - a pointer to something on the stack can't outlive the stack frame it points into.
> I don't see why anyone wouldn't copy values by default...
Because not everything is safe to copy. In particular, Rust has a few kinds of pointers which come with special rules.
Firstly, it has boxes, which always point to something on the heap, and have a rule that that when the pointer dies, the thing it points to gets freed. If you copied a box, then when one of the copies died, the thing would be freed, and then the other copy would have a pointer to invalid memory, which would be bad.
Secondly, it has mutable references, which come with a guarantee that a mutable reference is the only pointer to a given thing. If you copied a mutable reference, you would break that guarantee.
Thirdly, it has reference-counting pointers (these are in the standard library, not the language). You can make duplicates of those, but they have to increment their reference count when you do so. Copying is always just a bitwise copy, so there is no chance to increment the reference count. Instead, duplication is an explicit operation.
There are a few other things it doesn't make sense to copy. Like, what would it mean to copy a mutex?
So, in Rust, you can't copy by default. However, it is really easy to mark a type as being copyable (the compiler will check that it really is, ie doesn't contain any non-copyable things), and then you can copy it.
You can do the same to a pointer in languages that have them, either directly (e.g. in C) or through some "unsafe" construct (e.g. in Rust, C#, Go).
>I don't see why anyone wouldn't copy values by default... it is the only sane way to do things.
When resources are ample, yes. Not the case historically, or in many use cases today.
And not all values make sense to copy.
But also in Rust, we're talking in the context of C performance needs, memory models, and concepts, and Rust expands and makes those safe.
Pointer aliasing is not always obvious.
Re macros: try to keep an open mind if you can, C macros and Rust macros are completely different. You can get very far without reaching for them, so don't worry too much!
Had the same issue a few months ago.
The pointer can only be referenced by one variable at a time.
If you "move" the pointer from a to b then a is figuratively "used up" because a is now blocked from doing anything with the pointer anymore.
I guess, for Rust itself the pointer is still referenced by a, Rust just blocks you from using it. But thinking you moved it to another variable helped me a bit.
a = 2; b = a; c = a;
There's no pointer in there, just 2.
Someone needs to explicitly nail down the mission statement of Rust... because to me it seems to be
"Rust will introduce pointers where they don't need to be, and then try to protect you from the results with obsessive rules"
Hope it helps!
What '2 is Copy' means precisely that Rust WILL NOT 'introduce pointers where they don't need to be' - 2 is fine to 'alias' because it's a primitive type and so a copy is made when you do that, (i.e. the type implements the 'Copy' trait). However when you do that with complex types that do not implement Copy, you're moving ownership to the new variable so cannot use the old one any more.
Maybe playing around with the code would help you better, because that last line doesn't make any sense: https://play.rust-lang.org/?version=stable&mode=debug&editio...
The only exception to the above is if a type "is Copy". This means that values of this type can be copied very cheaply, and in this case the compiler will allow you to use it multiple times, which is implemented by it being duplicated on each use.
As for macros, they are nothing like C macros.
If you haven't already, check out the Playground: https://play.rust-lang.org/
It's reasonably full-featured for a web IDE (much more so than the Go playground), and it includes many commonly used packages.
> Because on my screen in non-dark mode...
The little sun icon in the lower left corner of the page turns on dark mode! Hopefully that helps.
> I don't understand why b=a; c=a; <-- doesn't work because a is "used up"???
This is something called "linear typing", and it's admittedly pretty unusual in a mainstream language.
The core idea is that the assignment operator _only ever_ creates a "shallow" (bitwise) copy of data; it never invokes anything like C++'s copy assignment operator. For types that are "plain old data" (like primitives), the old and the new values are fully independent, so the assignment works the same way it would in most languages, i.e., `a` is not "used up". This is what other commentors mean when they say that primitives "implement `Copy`". But if the old value has pointers or references, then the two values are not independent: after the bitwise copy, they both have pointers to the same data. Since data can only ever be shared explicitly in Rust, and the assignment operator never performs a deep copy, the old value, `a`, is considered invalid and cannot be re-used.
If you're familiar with C++11 or later, one way to think of it is that `=` in Rust always behaves somewhat like `std::move` in C++:
`b = std::move(a);`
The details are substantially different (this will call `a`'s move-assignment operator if one exists, which has no equivalent in Rust, and C++ offers no support for ensuring that `a` is no longer used if its move-assignment operator invalidates it). But the general idea that "move semantics are on by default" is essentially accurate.
It made me think of the days and weeks of debugging that I wouldn’t have needed to do, had Rust existed.
It's a bit annoying, but not much to do except slog through the guides and try to write a few programs.
let x: i32 = 42;
vs fn fair_dice_roll() -> i32 { 4 }
It seems the designers missed an opportunity, as the latter could quite easily have been: fn fair_dice_roll() : i32 = 4;
or fn fair_dice_roll() : i32 = { ... code that produces 4... }
at the slight expense of giving up the cutesy right-arrow. Maybe i'm just used to Prolog/Lisp code=data syntactic simplicity.And that's as far as I got as I exited the page scratching my head to write this comment.
val hello : String = "hello" // eagerly evaluated once
def hello : String = "hello" // evaluated every time
def hello(name: String) : String = s"hello $name" // parametersI personally like the arrow being used for return types as it highlights pretty well what returns stuff. I don't need to track fn definitions or anything when scanning a file - I just need to look for the arrows.
Having said that, when I've faced real challenges with Rust (and the borrow checker) it's been with bigger longer running applications, like a webapp, or a long running service.
I have no doubt part of that comes I have a stronger background in garbage collected languages, so my mindset when developing larger applications is in that mode. I'm sure with enough practice I'd get it, but there were many things that I just couldn't replicate one to one in Rust. Not that they weren't possible, but they were just different enough that I couldn't figure it out without being more comfortable in understanding the language, and I just haven't dedicated the time needed to it.
Will likely go back to it at some point, as it is an interesting approach to programming, with lots of upsides.
I may do another more complicated port soon. I love CLion.
Writing C code with Rust is a very different experience than converting C code to idiomatic Rust. There is more to porting than doing 1:1 conversions between keywords.
And by your description your utility basically reads words and prints their value. That doesn't really venture too much beyond the hello world territory.
"Your programs have access to two kinds of memory where it can store values: the stack and the heap."
They left out variables, which is odd.
Yeah, those are not mentioned. It also doesn't mention constant storage...
That said it's not like they're the bread and butter of programming for their lack of mention to be that "odd" as the parent implies.
(My low level knowledge is limited, may be completely wrong)
But in the most common languages, there is special storages for globals, statics, and constants, which is what the grandparent means (e.g. the DATA section).
https://github.com/rust-lang/rustlings
I spent the last two weeks going through it and so far the experience has been great. There's a quiz at the end of most chapters.
https://exercism.io/tracks/rust
It's also great to view other learner's solutions once you complete the exercise.
fn make_tester(answer: &str) -> impl Fn(&str) -> bool + '_ {
move |challenge| {
challenge == answer
}
}
why is there `move` needed, if both `answer`, and the arg of `Fn`, seem to be references (`&str`)? To a layman, this sounds like as if both "challenge" and "answer" should be borrowed - so why "move"? what's even to move here?> closure may outlive the current function, but it borrows `answer`, which is owned by the current function. To force the closure to take ownership of `answer` use the `move` keyword.
But 'answer' is of course not owned by the current function, and how can you take ownership through a shared reference?
The explanation is double indirection. By default, the closure captures a pointer to answer, which is itself a pointer on the stack. Without the 'move', inside the closure `answer` has type &&str and points into make_tester's stack frame. With the 'move', it copies the passed-in pointer. The error message is referring to the pointer itself, and this is not obvious.
Incidentally I have never found docs for the '+' syntax there, would appreciate a pointer to any.
This applies to impl Trait as well. It should probably be there too...
As you imply later, ‘answer’ itself is owned by the current function, but the ‘answer’ value is a pointer that doesn’t own what it points to. This subtlety, that references are full values themselves, is definitely something to trip on, especially when double indirection starts popping up like this.
I have a problem understanding how temporaries work in Rust. At least from what I see there is a difference between a temporary inside a vec that I bind somewhere to then pass it somewhere and a temporary inside vec constructed inside method invocation. I asked on SO [0], but did not receive satisfactory answer, or I'm too dense to understand it.
[0] https://stackoverflow.com/questions/64705654/why-i-get-tempo...
fn fair_dice_roll() -> i32 {
4
}
:-DI really like this. One of the things I like to do when learning a new language is to go to http://www.rosettacode.org/wiki/Rosetta_Code and just go through snippet examples for certain common tasks.
Just quickly going through examples to me feels much easier than trying to learn from principles.
Wish more language tutorials were exactly like this, no fluff.
> Called thusly because |_| () looks like a toilet.
Pure poetry!
Real talk though, this is a great introduction.
I find Rust's ? notation gives a very natural way of writing such algorithms. I don't care "why" filling in the Sudoku failed, particularly because the solver will typically fail millions of times a second, so I definately don't want constructing the error to be expensive in any way.
So in the context of programming languages, SRS might work if you need to memorize method names or method signatures (though I don't see why that is needed in the age of autocompletion and instant lookups from inside the text editor), but not so much for fundamental language concepts (like "how do lifetimes interact with the borrow checker").
Often, I end up being able to get started right away, but at worst, it gives me an accelerated start into tougher cookies like Rust.
https://en.wikipedia.org/wiki/Variable_shadowing
edit: I should've called it "variable redefinition" or something like that I guess, my mistake. Reassignment is definitely not the correct terminology for this.
Still, it's not shadowing because the new binding of 'x' is not effectively shadowing some other 'x' name, it's just taking its place in the same scope. And this is orthogonal to the memory allocation of the assigned objects.
let x = 1;
x = x + 1; // <- error[E0384]: cannot assign twice to immutable variable `x`
let mut x = 1;
x = x + 1; // ok!
This obviously matters very little for an integer, but it is relevant to more complex types.You can actually see the scopes, and the progress of variable liveness, if you run the compiler out to the MIR intermediate language:
fn main() -> () {
let mut _0: (); // return place in scope 0 at src/main.rs:1:11: 1:11
let _1: i32; // in scope 0 at src/main.rs:2:9: 2:10
scope 1 {
debug x => _1; // in scope 1 at src/main.rs:2:9: 2:10
let _2: i32; // in scope 1 at src/main.rs:3:9: 3:10
scope 2 {
debug x => _2; // in scope 2 at src/main.rs:3:9: 3:10
}
}
bb0: {
StorageLive(_1); // scope 0 at src/main.rs:2:9: 2:10
_1 = const 1_i32; // scope 0 at src/main.rs:2:13: 2:14
StorageLive(_2); // scope 1 at src/main.rs:3:9: 3:10
_2 = const 2_i32; // scope 1 at src/main.rs:3:13: 3:18
_0 = const (); // scope 0 at src/main.rs:1:11: 4:2
StorageDead(_2); // scope 1 at src/main.rs:4:1: 4:2
StorageDead(_1); // scope 0 at src/main.rs:4:1: 4:2
return; // scope 0 at src/main.rs:4:2: 4:2
}
}
https://play.rust-lang.org/?version=stable&mode=debug&editio...[1] The "Rust book" has a good explanation of shadowing, which contains a nearly identical example. See: https://doc.rust-lang.org/book/ch03-01-variables-and-mutabil...
The cheatsheets give me a quick intro to syntax conventions, and then the official documentation provides all the detail on specifics. I'm looking to mentally map how different PL constructs common across different languages are expressed in the new language I'm learning.
Along the way, I end up learning one or two new PL concepts. Fewer these days than in the beginning, hence it gets easier and easier to learn new languages.
I've never used Rust before so I'm exactly the target audience. I first got tripped up around
> Trait methods can also take self by reference or mutable reference:
impl std::clone::Clone for Number {
fn clone(&self) -> Self {
Self { ..*self }
}
}
What's the asterisk doing in this code? I guess it's destructuring the struct somehow, but I don't see that syntax elsewhere: destructuring was introduced but looked like it worked without the star. Alternatively, it's dereferencing the reference, but that seems less likely.Just want to take a moment a appreciate your efforts for writing this amazing article. Honestly it made it so easier to understand Rust especially for a beginner like me
Rust, Swift
let x = 42; let x = 42
let x: i32 = 42; let x: Int = 42
let _ = 42; let _ = 42
let pair: (char, i32) = ('a', 17); let pair: (String, Int) = ("a", 17)
let (some_char, some_int) = ('a', 17); let (some_char, some_int) = ("a", 17)
fn greet() { println!("Hi there!"); } func greet() { print("Hi there!") }
But, the languages are so different, for instance in Swift
let x x = 42
let y = 13 let y = y + 3
Wont fly for instance. I am trying to come up with the simplest explanation possible for this but I can't - goes to show how much I understand either of the languages.
Call me superficial but all the underscores and semicolons alone just feel like an eldritch summoning ritual in 2021.
I might write another one that focuses on the happy path.
I quite like the format (though this post is much better than mine) of lots of small snippets of code showing how something is used.
I'm proficient in C#. I haven't yet encountered any problems I can't solve with C# and the .Net open source ecosystem. (Perhaps that says more about the banality of the problems I'm solving than about .Net, but there you are.)
What would Rust give me the tools to do that I can't already accomplish with C# / .Net Core?
If you're primarily doing app dev work, be it desktop or web, you wouldn't really benefit much from it. Although I think Rust code can be compiled to wasm so you could use it as part of webdev work.
You might also find this an interesting read from the same author: https://fasterthanli.me/articles/i-am-a-java-csharp-c-or-cpl...
This looks like a fun and useful article, but I'd also recommend Rustlings to anyone interested in learning Rust.
https://gist.github.com/ityonemo/769532c2017ed9143f3571e5ac1...
let x;
foobar(x); // error: borrow of possibly-uninitialized variable: `x`
x = 42;
possibly-uninitialized - Why does the compiler sound uncertain while emitting an error?It also is language that works well when something may be initialized in some control flow paths but not all.
>A rust device driver for the Bosch BME280 temperature, humidity, and atmospheric pressure sensor and the Bosch BMP280 temperature, and atmospheric pressure sensor
You probably want to add feeling_lucky: bool as an argument to fair_dice_roll()
Oh, I guess it's a year old - but still, extremely good.
It's like Ultima Online back in the day. Everyone loved it but every time I tried i fell asleep and just couldn't get into it.
I'm semi happy with Go. It's a hands on language that is fast enough. But it's missing elegance and something I can't put my finger on is missing.
But Rust, it feels like a step back. What do I think in? Boxes? Wrap unwrap move what? It's so hipster I just hate it. And compilation takes a lot of resources and time. Hell, Java makes more sense to me than Rust.
And why all those macros? And impl for order is backwards. Why couldn't the word class be used, no they just want to be different for the sake of being different. It's a language for hipster rebels without a cause.
The extreme degree of shared syntax and shared semantics with Scala was really surprising to me.
A lot of Rust’s language people did a lot in Scala. The language’s are pretty different IMHO.
Rust seems like when C++ marries Scala.
Disclaimer: I like C, Python and Scala but not a big fan of C++ and Java