14 ms·
Rust 1.42
- throwlaplace 7y agocan I poll the audience of seasoned rust devs: how do you deal with the borrow checker and lifetimes? do you simulate both in your head before writing your code or do you just let the compiler yell at you and then silence it by fixing bugs? I ask because I've written some trivial rust code (a little TUI client for a database) and while it was mostly fine, I didn't feel myself absorbing the rules by osmosis (I had to wait for the compiler to yell at me and then wrestle).
- burntsushi 7y agoI'm not sure if it's a simulation so much as the rules just become normal constraints you use when writing code. It is super rare for me these days to write any line of Rust code that makes the borrow checker complain in a way that surprises me. It took me a while to get to that point. I don't remember how long though.
- throwlaplace 7y agoany suggestions for exercises that drill this in? I'm going through the linked list book but it's still not completely transparent for me.
- burntsushi 7y agoNot really. Pick a project and start building. At least, that's my learning style. Reading things like the linked list book is great, but eventually, you probably have to put it to practice in order to really learn it (like most things).
- steveklabnik 7y agoI would like to second everything you've said here, and add a few things: 1. If you are feeling stuck, please reach out on users.rust-lang.org or discord.gg/rust-lang. We're here to help! 2. If you're feeling really stuck, maybe take a break and come back to Rust in a few months. A number of people have given up on Rust in frustration, came back after a significant amount of time, and then said "why did I think that was so hard before?" 3. Don't worry about a few calls to clone when you're getting started; it's better to have a working program that does some extra copying than it is to not have a program at all. 4. Especially when starting out, you almost always want structs to own their data. Don't use references as struct members unless you're absolutely sure that's what you want. Advice #3 helps with this. 5. I think one of the biggest mindsets that can set you up for failure with Rust is "The compiler says no, how do I get it to do what I want anyway" instead of "The compiler says no, what is it telling me, and how can I work with it instead?" Especially if you come from an OO heavy background, you may need to change the patterns that you reach for initially. Yes, you can write any style in any language, but Rust pushes you towards its idioms much more strongly than other languages do.
- burntsushi 7y agoHah yes, this is a MUCH better answer. Thank you. :-)
- steveklabnik 7y agoNaw I think you hit the most important bits right up front :)
- CameronNemo 7y ago>discord.gg/rust-lang Why not plug the rust channel on Matrix?
- steveklabnik 7y agoI only plug: * Things that are run by the project * Things that I use I have no idea if the Matrix channel is any good or not, so I cannot recommend it.
- hechang1997 7y agoI found the "Too Many LinkedList" tutorial is very helpful. Try to follow the tutorial by writing your own code.
- GolDDranks 7y agoLifetimes are not actually that hard: it's mostly stack discipline, with some escape hatches. The compiler yelling at me is mostly stupid, surface syntax like things, but that's because I've learnt naturally to structure my code in a way that makes sense with stack discipline. Over 5 years of Rust experience, 2 of which are professional.
- hathawsh 7y agoThe key, I think, is to figure out which kinds of Rust patterns are ambitious and efficient if they work, versus patterns that are easy to write and unlikely to fail. It's tempting to use references everywhere possible for efficiency, but Rc, Arc, Cell, RefCell, Mutex, and other smart pointer types can get you out of a jam. Sometimes you just have to bite the bullet and clone things until you've figured out a better way. Looking back at the very first Rust module I wrote, it's actually not half bad. I thought it was bad at the time because I was continuously fighting the borrow checker, but now I see that the borrow checker led me toward fairly idiomatic Rust patterns. BTW, if you're coming from Javascript or Python, the closest thing to a JS/Python string in Rust is Rc<String> or Arc<String> (depending on whether your code is multithreaded.) I don't want to admit how long it took me to figure that out and I think that little bit of wisdom ought to be featured prominently in the Rust book. :-)
- saagarjha 7y agoI would steer you away from Rc and Arc unless you know you need them.
- hathawsh 7y agoPerhaps. I can think of a couple reasons to steer people away from Rc/Arc: they are less efficient than references and they don't support cyclic garbage collection. On the other hand, Rc/Arc are very helpful for newcomers coming from garbage collected languages and they can be more efficient than cloning. If I asked an employee to convert some high level module to Rust and that employee used a lot of Arcs where they weren't really necessary, I would say that employee had done a reasonably good job.
- pjmlp 7y agoThey are unavoidable with most GUI bindings on Rust, actually it is a plethora of Rc<RefCell<>> across the code.
- _never_k 7y agoBefore rust, I would incrementally evolve an incomplete design into a complete design (building a tree by building leaves, branches, and a trunk and then assembling them.) In rust, my early incremental versions would have lifetime issues that I used to not worry about until later. Now I start with a very small complete version that I make bigger (building a tree by increasing the size of a sapling.) I do everything this way now (JS, python, etc...)
- ufmace 7y agoI honestly haven't felt like it was much of a problem. IMO, the main thing to understand is that Rust strongly prefers that each instance has one and only one owner at any time, and any references to that object should only exist for a strictly constrained amount of time. This is the preferred style, and doing anything else, including some patterns common in other languages and OOP, will be very painful. Don't be afraid to throw clone() around with reckless abandon any time references get confusing, most things are cheap and fast to clone, and it's generally better to get your program working now and then optimize as needed, rather than try to figure out how to handle a weird case.
- _-___________-_ 7y agoWriting rust since ~2016, doing a lot of async/await and multithreaded stuff and using explicit lifetimes quite often. At the beginning it was a case of write the code, then see how the borrow checker complains and fix it. Now that I understand the semantics intuitively, for the last year or so, it's very rare for the compiler to complain about anything. I guess I've internalised the semantics -- they're not exactly arbitrary, mostly the lifetime rules just follow from what you should be doing anyway. One thing I would encourage (and this applies in general) is trying to understand _why_ the compiler is complaining about some code you wrote before attempting to "make the error go away". Don't just hammer away until you make it work; that's not how you learn. I've seen a lot of Rust code that's full of unnecessary use of Cell, Rc, etc because people didn't take the time to understand the semantics and just reached for ways to "make the errors go away".
- est31 7y agoVery grateful about the better unwrap location reporting. This has annoyed me last this week. Didn't know that it was being stabilized (only checked the track_caller tracking issue which is still open) so I'm very happy now :).
- atoav 7y agoA good idea usually is to use unwrap only if you know there is no logical way for it to blow up and to use .expect("My Message explaining why this blew up") everywhere else.
- howenterprisey 7y agoThe matches! macro looks awesome! Looking forward to using it a lot (especially to check variants).
- bonzini 7y agoif let is usually good enough to check variants. Matches! should be useful to implement methods like is_some() or is_ok(). Also for assertions, but then again there is a crate that provides assert_matches!, which is more useful for this than matches! itself.
- nathcd 7y ago> Due to our stability policy, `description` will never be removed .. Can this sort of removal not happen as part of an edition? Is it because it's part of std, rather than core, or something like that? It's a bummer, but the commitment to stability is appreciated! matches!, subslice patterns, and .unwrap messages look excellent!
- steveklabnik 7y agoThe standard library cannot change per-edition, that's correct.
- GolDDranks 7y agoI guess that it _would_ be possible to have a hard "edition lint" that would basically forbid you from _implementing_ description in a 2021 or whatever crate. It would still exist and be callable, but no new (non-default) implementations if you want to use new editions.
- burntsushi 7y agoEditions do not permit arbitrary breaking changes. Notably, the same version of std must work across all extant editions of std. For example, many people use the `regex` crate in their Rust 2018 projects despite the fact that `regex` still uses Rust 2015. If Rust 2018 made a breaking change to std, this wouldn't be possible in general.
- est31 7y agoYou could add an edition sensitive non-overridable error to the language, as in, if you use it on edition 2015 or 2018, there is no problem, but on edition 2021 and beyond there will be an error in your code that you can't allow away. Then you could have edition specific rustdocs for std where items that are deprecated this way are hidden per default. However, at least the 2018 edition had the requirement that updating can be done automatically. Ensuring that is hard for library functions.
- 7y ago
- computerphage 7y agoBetter line numbers is huge. Actually huge for people leaning rust. In a pretty big way it's like the difference between Java where you get a stack trace (where you mostly care about the live number all the way at the bottom) and C++ where you don't. When I tutored students in college that was one of the most salient differences to students who were just starting out. They would say things like "C++ is hard because you don't even get a stack trace". Sure, that's a naive view of the differences between the languages, but it's a real view that beginners see.
- jcelerier 7y ago> and C++ where you don't what do you mean ? in which case don't you get a backtrace in C++ ?
- neutronicus 7y agoIf you compile without debug symbols you don't get a trace after a seg fault. If you're taking first year programming and they give you a compiler incantation that doesn't include -g that will be your experience.
- saagarjha 7y agoThat's just a poor default, I guess. Rust compiles debug builds unless you tell it not to.
- neutronicus 7y agoThis may have changed since the days of my youth
- umanwizard 7y agoWhether a build is debug or release is independent of whether it contains debug symbols. Both `cargo build` and `cargo build --release` produce builds with debug symbols.
- saagarjha 7y agomatches! looks quite useful, I’ve been looking for a replacement to Swift’s ~= operator and this should do nicely.
- mmastrac 7y ago> Due to our stability policy, description will never be removed, and so this is as far as we can go. What Rust _should_ do is gradually increase the noisiness of warnings about using this. Eventually it'll disappear from the crate and end-user ecosystem (possibly with a small effort to tidy up abandoned crates). Java's "never remove a deprecated API" was definitely one of their big mistakes. Even a 10-year deprecation cycle is better than none.
- baby 7y agolook at the monster that C++ is now because of this as well. I think this is why people are turning to Golang, Rust, and Swift. But these languages could follow the same path.
- saagarjha 7y agoThose three languages also happen to have memory safety.
- jhasse 7y agoAnd other features that differentiate them from C++. But I think that was the OP's point: People are switching to other languages mainly because C++ has become a monster, not because of missing memory safety.
- jolux 7y agoI don't think that's the whole story. Golang is mostly picking up programmers from dynamic languages, according to Rob Pike, and Swift is gaining steam mostly because Objective-C while not monstrously complex like C++ is incredibly verbose.
- pjmlp 7y agoSwift is gaining steam, because Apple dictates it, unless one enjoys using a frozen language. Likewese using C++ on Android requires perseverance given the how the NDK is handled and what it exposes, while on Windows it feels nice because it has parity with .NET tooling, specially on UWP.
- edflsafoiewq 7y agoCompletely pointless tangent: the article uses `unwrap`ping as the -ing form of `unwrap`. That looks weird to me. It occurs to me that `X`->`X`ing is a better rule because of things like `leave`ing (not `leav`ing).
- saghm 7y agoMy guess is that they used that spelling because "unwrapping" is a real word, and that's how it's spelled. Tangentially, the word itself is spelled that way to preserve the vowel sound of "unwrap"; without the second "p", the "a" sound would turn from a short "a" to a long "a". A good heuristic for this sort of thing is that a syllable that ends with a consonant will make a short vowel sound, whereas one that ends with a vowel will have that vowel sound be long.
- steveklabnik 7y agoYes, that's exactly why.
- foldr 7y ago>My guess is that they used that spelling because "unwrapping" is a real word, and that's how it's spelled. Yes, obviously, but you're missing OP's point. When the keyword is backticked it doesn't really make sense to adjust its spelling based on the addition of the -ing affix, since in some cases this would also require deletion of letters at the end of the keyword -- which clearly should remain unaltered when backticked. Thus, the only sensible and consistent rule is not to make spelling adjustments when adding -ing to backticked keywords. Not that any of this matters at all!
- asplake 7y agoOften, avoiding ‘ing’ reads better anyway. “More useful messages when unwrap() panics” would have been fine.
- _-___________-_ 7y agoRight: in my mind, by putting the () there, they're basically making it shorthand for "More useful messages when the `unwrap` function panics"
- _bxg1 7y agoI didn't realize how rich the normal match { } patterns can get until I saw these matches!() examples and was trying to figure out what that pattern syntax was. I've only ever used the basic enum matching/enum value unwrapping patterns.
- steveklabnik 7y agoIt can do a lot of stuff! https://doc.rust-lang.org/stable/book/ch18-03-pattern-syntax.html https://doc.rust-lang.org/stable/book/ch18-03-pattern-syntax... (This will need to be updated to include the things in this release, but I haven't gotten to it yet.)
- sdegutis 7y agoA similar macro the stdlib should have is poor_mans_cast!(foo as Bar::Qux) which expands to match foo { Bar::Qux(x) => Some(x), _ => None }.unwrap() which is a questionably-hacky way to cast to a specific enum variant. I've had to use it twice because I couldn't figure out a more Rust-like way to solve the problem at hand.
- steveklabnik 7y agoCould you maybe whip up an example on https://play.rust-lang.org/ https://play.rust-lang.org/ ? It's not 100% clear to me what you're doing here, but I'm interested!
- sdegutis 7y agoThink for example of implementing a list interpreter. In certain situations, you know for a fact that an AST node is a given type. So you just want to cast from Node to Node::Symbol(s) to extract that std::string::String out of it. RFC #2593 seems like it would help here, and is something I've wanted for similar but unrelated reasons. So in the meantime I made poor_mans_cast!() macro to do this, which I've used twice already.
- bombela 7y ago
- unlinked_dll 7y agoCan we use #[track_caller] on procedural macros?
- SpaceManiac 7y agoYour macro can expand to line!() or file!() calls as needed, which will reflect the call site.
- anp 7y agoWhat a great question! Because it's implemented as a const/codegen feature I'm not sure what it would mean to support it for proc macros. Probably gnarly design/RFC work?
- dpcx 7y agoAs someone who's getting in to Rust, does anyone have suggestions on blogs or people on Twitter to follow that would be good for continuing to push the envelope of my knowledge of Rust? I've got a couple, but I'd love more.
- steveklabnik 7y agohttps://readrust.net/ https://readrust.net/ collects blog posts.
- agacera 7y agoNot a blog or a Twitter, but Jon Gjengset channel on YouTube has awesome live (or records of) coding videos on Rust. The topics are not for beginners, but even thought I'm starting on Rust as well, I've found his videos an excellent resource. https://www.youtube.com/c/JonGjengset https://www.youtube.com/c/JonGjengset
- PudgePacket 7y agoGo to rust subreddit, sort by top for the month, read the top few blog posts every so often. Otherwise, read through the blog posts listed in previous editions of https://this-week-in-rust.org/ https://this-week-in-rust.org/
- FullyFunctional 7y agoI'm very excited about this change: "Added tier 2 support for riscv64gc-unknown-linux-gnu" which hopefully means Rust will make its way to the RISC-V versions of Fedora/Debian (wasn't there when I last checked). Furthermore, there are a lot of things depending on this that might also arrive now.
- nickysielicki 7y agoI don’t really like that procedural macros are a thing. Rust isn’t quite at the Go level of forcing style, but it’s closer to it than it is to C++ or C, and I think the ability to implement DSLs with procedural macros makes it harder to look at code and understand what it does. I guess I’d rather have the feature for when it’s truly necessary than exclude it from the language entirely, and just hope that people use it with forethought.
- steveklabnik 7y agoNo procedural macros means that libraries like serde and diesel cannot exist. Or at least, they would have to exist in a much worse form. This was true before Rust 1.15, when the first parts of procedural macros were stabilized. I remember the release specifically because things got so much better after this was possible.
- lmm 7y agoA macro is a bug report against the language; Rust is crying out for a way to treat structs generically (i.e. what frunk does with LabelledGeneric), but that only needs to be implemented once. There's no reason serde and diesel couldn't be built on top of frunk (that's how many things work in the Scala world: specific libraries like circe or pureconfig don't write custom macros, they just pull in a dependency on Shapeless) - and then once there was a clear consensus on the right way to do it, LabelledGeneric or equivalent could be made a standard part of the language and no macros would be needed at all. Maybe macros make sense as a pragmatic way to allow prototyping of future language features. But language designers can, and IMO should, work towards making them unnecessary in the production-code ecosystem, because the disadvantages for readability and tooling are very real. And that's only going to get worse as more advanced tooling (IDEs, profilers etc.) becomes available and people rely more heavily on those tools to be deeply integrated with the language, because those tools are never going to be able to understand ad-hoc macros.
- Arnavion 7y ago>Rust is crying out for a way to treat structs generically (i.e. what frunk does with LabelledGeneric), but that only needs to be implemented once. There's no reason serde and diesel couldn't be built on top of frunk [...] What frunk does at runtime (well, its proc macros are still compile-time, but the code that makes use of the metadata is runtime), syn does at compile-time. I can understand that it's nice to have a simpler model where everything happens at runtime, but the things that proc macros can do include things that matter to the typesystem. For example, some of the macros I've written generate new types based on the input tts. You can't do that at runtime. >And that's only going to get worse as more advanced tooling (IDEs, profilers etc.) becomes available and people rely more heavily on those tools to be deeply integrated with the language, because those tools are never going to be able to understand ad-hoc macros. The mainstream tools (rls and rust-analyzer) get their information from the compiler, and thus have access to the expansion of the macro rather than just the macro invocation.
- unexaminedlife 7y agoI'm curious to know if anyone who regularly uses Rust could speak to a theory I have on the language. I'm by no means an expert but I've dabbled enough to know Rust is I think going to be far more important to the world than it is already. I'm planning to dive back into it, but this time I'm going to attempt to do all of my programming in such a way so as to not require 'lifetime' semantics. Not 100% sure how easy it would be to do so, but the theory is that maybe writing code that needs lifetime semantics is an anti-pattern? Rust has just given us the tooling so we can confirm that the "style" we are already writing our code in adhere's to Rust's guarantees...
- _-___________-_ 7y agoUsing Rust daily since ~2016 here. I'm assuming that by "writing code that needs lifetime semantics" you mean "writing code that needs explicit lifetimes", since all code in Rust has some lifetime semantics going on. If I've misunderstood then please clarify. Lifetimes are one tool in the toolbox, and using them is absolutely not an anti-pattern. Being able to define and use explicit lifetimes is a really powerful tool that allows you to safely share data in ways that can be tricky and error-prone to do in some other languages. For example, a deserialiser could be passed a reference to a buffer (&'a [u8]) and return a struct where some fields are &'a str which are just bytes borrowed from that buffer. You could then perhaps trim() them - returning another &'a str which just points to a smaller slice of that same buffer, and pass them off to other parts of your program - potentially even pass them to an async function that you await on, which could run in another thread - and the explicit lifetimes mean your code will fail to compile if the buffer can be dropped before the string is.
- unexaminedlife 7y agoYou're right. I worded that ambiguously. Thanks for the feedback (all comments).
- mikekchar 7y agoI'm not a proficient Rust programmer yet, but the thing I've been finding is that previous programming experience often suggest solutions that require lifetimes. These solutions are often inappropriate. I think as one becomes more fluent in Rust oriented solutions, it will become more obvious that there is a better way to approach the problem. It's not so much that the use of a lifetime is indicative of poor code. It's more that due to lack of experience in the Rust way of doing it, you are more likely to reach for lifetime solutions that are inappropriate. Trying to avoid them at all cost as a novice seems like a good way of finding out where you absolutely need them (and, in my experience, there are definitely many such places). It sounds like a good exercise.