26 ms·
A half-hour to learn Rust
- mcc1ane 6y agoLost me at around 40% - suddenly "immutable references", "mutable references", "borrowed implicitly"...
- timhigins 6y agoA half-hour to learn Rust Jan 27, 2020 · 51 minute read · rust maybe the site's reading time estimator is broken? sarcasm intended. But seriously, it is good to have people writing things like this.
- internet_user 6y agohalf-hours is only the compilation time.
- pwdisswordfish6 6y agoPer snippet.
- fasterthanlime 6y agoSarcasm aside, the Rust compiler has gotten a lot faster (and parallelizes better) over the last year thanks to Nicolas Nethercote and others. 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.
- swazzy 6y agoI'm guessing the code snippets are skewing the estimate.
- GreenWatermelon 6y agoIf anything, code snippets take time to parse and understand what every word and symbol mean. I kept going over "traits" because I didn't get them at first.
- AlchemistCamp 6y ago> maybe the site's reading time estimator is broken? All of them are. I first started disliking Medium for just that reason.
- keyle 6y agoProgrammers don't read, they skim in half the time, then auto-complete in their mind with false assumptions!
- techsin101 6y agohey get out of my head
- deleted 6y ago[deleted]
- Fannon 6y agoIs there a name for this behavior? Sounds like something that is categorized as a cognitive bias? I'm confident that this does not only apply to programmers :)
- coldtea 6y agoIt's the cognitive bias cognitive bias (the idea that every random mistaken behavior can be categorized as a congnitive bias).
- brabel 6y agoThat would explain so many of the comments you read on HN and Reddit!
- pjmlp 6y agoAnd then try to write a GUI in Rust.
- artursapek 6y agoThe state of that art is improving quickly: https://github.com/hecrj/iced https://github.com/hecrj/iced
- pjmlp 6y agoDoesn't do localization or integration with assistive technologies of the host platform, does it?
- oblio 6y agoFirefox' reader mode estimates it at 35-45, if that helps :-)
- coldtea 6y ago>maybe the site's reading time estimator is broken No, it's just made for prose, not tutorials.
- fasterthanlime 6y agoYep, code is a lot of "words" which throws off the estimate. I need to address this, but I don't think completely ignoring code blocks is really the solution there.
- kangalioo 6y agoMaybe you could estimate the reading time of a code snippet by taking the square root of the number of lines of code? I imagine that the larger the code snippet, the more irrelevant boilerplate it contains, so the square root might be a good way to model this
- stonecharioteer 6y agoI worked my way through the entire article, typing in each code example. Took me about 3 hours.
- saghm 6y agoWell, it does say "reading time"; I don't think the estimator expects people to write the article as well!
- eeZah7Ux 6y ago> maybe the site's reading time estimator is broken? sarcasm intended. It was not rewritten in rust?
- k1t 6y agoIncredible. Great job. Oh, I guess it's a year old - but still, extremely good.
- dimmuborgir 6y agoPrevious discussion: https://news.ycombinator.com/item?id=22448933 https://news.ycombinator.com/item?id=22448933
- mrlonglong 6y agoIt only took me a couple of hours to port one of my old C programs, an utility to produce a hexadecimal and ASCII dump to Rust. The Borrow checker didn't even faze me. All I needed was plenty of Google-fu and my coding skills. JetBrains CLion and git are also very useful tools.
- chamakits 6y agoI had a similar experience porting a relatively straightforward and simple CLI utility I had written in C. 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.
- mrlonglong 6y agoMy biggest issue was trying to print the contents of u8 as a character. In the end this was actually as simple as writing print!("{}", line[i] as char), no print specifiers needed. I may do another more complicated port soon. I love CLion.
- rualca 6y ago> It only took me a couple of hours to port one of my old C programs, an utility to produce a hexadecimal and ASCII dump to Rust. 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.
- mcsalgado 6y agoIn the 9th code snippet that's not an example of variable shadowing, it's just variable reassignment. Shadowing involves variable assignments in different scopes. https://en.wikipedia.org/wiki/Variable_shadowing 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.
- stormbrew 6y agoThere is effectively an implicit scope created by the let binding. In rust you can't reassign a variable without it being mut. The two `x`s are separate variables named x and are not at any point mutated. Reassignment would look like this: 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&edition=2018&gist=8af2f63e25b8bc8bfdb43c1908cf7da4 https://play.rust-lang.org/?version=stable&mode=debug&editio...
- wintorez 6y agoAnother great resource: https://learnxinyminutes.com/ https://learnxinyminutes.com/
- deleted 6y ago[deleted]
- skc 6y agoThis is actually fantastic. Wish more language tutorials were exactly like this, no fluff.
- johnisgood 6y agoYeah, and it looks quite beautiful!
- Animats 6y agoThat is the best article on Rust I've ever seen. Better than the Rust book. I've been saying that Rust needed a book that wasn't written by the designers of the language, who are too close to it. Now we have one.
- tgv 6y agoBut it only covers the very basics. Disclaimer: I've only scrolled through it, but the code snippets are all small. It does show an admirable amount of Rust's syntax, but it's not very discoverable, whereas the book is reasonably well structured (although not for novices, who have forgotten a specific term). The link also doesn't deal with larger programs: there's not an Rc<T> on the page, let alone something like an Arena and unsafe code, and it's really necessary for complex programs. 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.
- trumpeta 6y agoThere are plenty of cases where you can write a complex program in Rust without ever needing those things.
- lordnacho 6y agoI've favourited the article. It's a good complement to the Rust Book, which has more detail. This kind of summary doc is great for discovery, you skim it and you find something that you could have written differently, or you realise there's an idiom you weren't using. No substiture for the book, though.
- EugeneOZ 6y agoIt's your opinion and I'm not arguing: a lot of people love the Rust book, but some (including me) simply can’t read it because of the style of writing and cases when you discover some interesting and deep topic but the author just gives 1 example in 5-10 lines of code and that's all. I think that things like Mutexes or Boxes are deep enough to have 30-50 pages dedicated to them, and I can say this not only about Mutexes and Boxes. When explaining some powerful things, one need not only explain how they work, but also what kinds of real tasks they can solve - ways of usage are obvious for you when you know it and have experience of usage them, but absolutely opaque and not obvious when you reading about them for the first time.
- nindalf 6y ago> And here's a toilet closure: |_| () > Called thusly because |_| () looks like a toilet. Pure poetry! Real talk though, this is a great introduction.
- jerrre 6y agoI've been staring at this for a minute, but please help me seeing a toilet in this? Is it a top down view perhaps?
- kyrrewk 6y agotoilet seat up
- jackric 6y agowhich bit is the toilet seat?
- AlexSW 6y agoThe seat is to the right (the ( )) and the water tank (?) is on the left.
- matt_kantor 6y agoI made a visual: https://i.imgur.com/VgsDidE.jpg https://i.imgur.com/VgsDidE.jpg
- jackric 6y agoMuch appreciated!
- CJefferson 6y agoI often use the "owl" <(),()>, usually in Result<(),()>.
- redisman 6y agoThere wasn't anything on concurrency or asynchronous programming (like a http client). Is there a good resource for those parts of the language?
- fasterthanlime 6y agoThe closest I've written is this: https://fasterthanli.me/articles/getting-in-and-out-of-trouble-with-rust-futures https://fasterthanli.me/articles/getting-in-and-out-of-troub... but it explicitly seeks the complicated bits because elucidating those is the whole point of the article. I might write another one that focuses on the happy path.
- deleted 6y ago[deleted]
- wokwokwok 6y ago> There is a special lifetime, named 'static, which is valid for the entire program's lifetime. 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/static_lifetime.html#static https://doc.rust-lang.org/rust-by-example/scope/lifetime/sta...
- DougBTX 6y ago> These are totally different things with the same name. 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.
- GolDDranks 6y agoThe wording that "'static means different things" is a bit misleading. It means the same thing, but the meaning different because of the context: 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.
- wokwokwok 6y agoI find it very confusing. 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.
- blargmaster42_8 6y agoCan't take anyone that uses if(..){ Notation seriously.
- vghaisas 6y agoIn college, I wrote something sort of like this to help students prepping for interviews in C++: https://vghaisas.com/code-quickref/cpp.html https://vghaisas.com/code-quickref/cpp.html 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.
- sanmak 6y agoSnippets looks quite impressive. But if it's segregated into different post like https://flaviocopes.com/ https://flaviocopes.com/ did, then it'll be much helpful.
- Barrin92 6y ago>In this article, instead of focusing on one or two concepts, I'll try to go through as many Rust snippets as I can I 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 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.
- elvongray 6y agoReminds me of this also: https://cheats.rs/ https://cheats.rs/
- malwrar 6y agoThis is precisely what I was looking for when I searched for “Rust for C++ programmers” in the past. I love the Rust book, but I’ve always thought the common focus on accessibility for newbie programmers made it feel tedious for those who are more seasoned. I’d love to see more writing like this, maybe even for other things like libraries!
- bluejekyll 6y agoI found the Rust book to be anything but tedious, as a seasoned programmer. As I read it, it made me want to cry thinking back on past bugs and issues that I had dealt with that the language had been designed to prevent. It made me think of the days and weeks of debugging that I wouldn’t have needed to do, had Rust existed.
- pascalgn 6y agoIf you already know C++, https://overexact.com/rust-for-professionals/ https://overexact.com/rust-for-professionals/ might be for you (disclaimer: I wrote this)
- morrbo 6y agoI prefer your guide if it is any consolation. Thanks for writing it
- ufmace 6y agoI've found it's generally really tough to find guides for getting into new languages that are written for experienced programmers who don't know that language yet. Everything seems to be written for complete newbies, or be a dense reference that assumes you know almost everything already. It's a bit annoying, but not much to do except slog through the guides and try to write a few programs.
- tsjq 6y agoVery well said. Totally agree with this point. I experience the same.
- 6y ago
- hawski 6y agoIt's a great resource. I like such easy list approach, because many times new language just needs a translation from concepts you already know. 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-temporary-value-dropped-while-borrowed-if-i-assign-but-not-when-pas https://stackoverflow.com/questions/64705654/why-i-get-tempo...
- jokethrowaway 6y agoThis is great! You probably want to add feeling_lucky: bool as an argument to fair_dice_roll()
- dperalta 6y agoThis is exactly what I need it <3
- mraza007 6y agoLiterally the most easiest way to understand Rust. 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
- IshKebab 6y agoThis is very good although the title definitely promises too much!
- mojuba 6y ago(Side note: dear Apple, please add syntax coloring and code formatting for Rust to Xcode. You have Fortran and C Shell in the list, but not Rust or Go, which are much more popular!)
- speedgoose 6y agoIs there any reason to use Xcode for Rust development?
- mojuba 6y agoIt's a habit. Keyboard shortcuts, familiar bugs and glitches, etc are not easy to change.
- mikewarot 6y agoI was a complete Nube an hour ago... I understand info from Nubes has special value, so I'll be as explicit as I can. 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.
- strictfp 6y agoRust is tricky. Took me about a year to grok decently. 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.
- coldtea 6y ago>I don't understand why b=a; c=a; <-- doesn't work because a is "used up"??? 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...
- mikewarot 6y agoI've only had a passing acquaintance with C and C++, so I've never used aliases. 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.
- inancgumus 6y ago[dup] duplicate https://news.ycombinator.com/item?id=22448933 https://news.ycombinator.com/item?id=22448933
- dmurray 6y agoGreat article. 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.
- pornel 6y agoIt is dereferencing. It changes `&self` to `self`. The `..` operator wants a value, not a reference.
- Aeolun 6y agoSo the & and * can basically be left out to make ‘self’ a value from the start?
- rcxdude 6y agotechnically yes, but it'll change the semantics in a not useful way. Because if you leave off the & on self then the method won't borrow self (take it by reference) but consume it (take it by value by 'moving' it), so you can't use it any more after calling clone(), which basically makes the method a no-op instead of copying the struct.
- dmurray 6y agoThanks pornel and rcxdude, this makes sense to me now. I was thinking it shouldn't be dereferencing because when references were previously introduced (the print_number example), we could call methods on the reference without any special syntax. But I guess it makes sense that instance methods work that way, while other functions need to know if we have a reference or the real object, and in this regard it works more or less like C++.
- 6y ago
- Aeolun 6y agoWhen I read these articles everything always seems so understandable, but I can pretty much guarantee that I won’t remember much tomorrow.
- axihack 6y agoSame with me, to learn anything I need to write it down, possibly several times.
- stonecharioteer 6y agoI recommend typing out the entire article as in into an editor. After you work your way through it, try the rustling course, Rust by Example, the CLI tutorial and then read The Book.
- pddpro 6y agoHave you tried Anki or similar Spaced Repetition System?
- majewsky 6y agoSRS is really good for learning small, compartmentalized knowledge items. Its usefulness degrades quickly when you move from knowledge to concepts. I'm currently learning Japanese and using several SRS tools to do so. The ones that work the best are for characters and vocabulary. I also use one for grammar, which is okay-ish but doesn't translate as well to the SRS format. 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").
- mkl95 6y agoI like Derek Banas' approach. He makes introductory videos for several languages. They are suited for developers who already have some experience in another language, and they last from 45 minutes to 2 1/2 hours. https://www.youtube.com/watch?v=U1EFgCNLDB8 https://www.youtube.com/watch?v=U1EFgCNLDB8
- Tade0 6y agoThere's a lot of valuable, condensed knowledge here, but for those who wish to learn the language in a more interactive way I recommend Rustlings: https://github.com/rust-lang/rustlings 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.
- noisy_boy 6y agoI have been doing the rustlings exercises (which are basically exercises to fix errors on various topics) - they are just the right size to keep you engaged and continuing because they reward you with success. Also its very easy to leave it anywhere and resume exactly the same point or go back to an old exercise and retry it. Plus because its just code organized in a directory, you can leverage all the feature of your favorite IDE. Highly recommended.
- miccah 6y agoI have been learning rust interactively with Exercism, which uses a mentor system to provide feedback and suggestions. https://exercism.io/tracks/rust https://exercism.io/tracks/rust It's also great to view other learner's solutions once you complete the exercise.
- kliments 6y agoThank you for this comprehensive article! Definitely reading and saving it for future reference.
- Sander3Utile 6y agoHere is another similar resource for learning new programming language's on the fly https://learnxinyminutes.com/ https://learnxinyminutes.com/
- stonecharioteer 6y agoI spent a few hours typing this entire article into an editor just to build muscle memory and I'm amazed. It's exactly the sort of article I needed to learn Rust. I've since thanked Amos on Twitter and I've forwarded links to his blog to a lot of people. This is a great article and does a good job clarifying things to a newcomer.
- pddpro 6y agoThank you so much for this. I wonder if similar guides exist for languages like Go and Julia.
- bbx 6y agoIn similar fashion you can learn “Web Design in 4 minutes” [1] and “JavaScript in 14 minutes” [2] [1] https://jgthms.com/web-design-in-4-minutes/ https://jgthms.com/web-design-in-4-minutes/ [2] https://jgthms.com/javascript-in-14-minutes/ https://jgthms.com/javascript-in-14-minutes/
- emerged 6y agoThis seems good but it starts using borrow in a bunch of examples without saying what it even is.
- laydn 6y agoWhat I would like to also see in these types of well written articles is the answer to questions like "what can you do with Rust that you can not do with C?"
- pjmlp 6y agoHaving to ask for permission to corrupt memory.
- psanford 6y agoWrite code that is memory safe.
- fasterthanlime 6y agoThis may answer part of your question — it's focused on strings but draws parallels with C all along: https://fasterthanli.me/articles/working-with-strings-in-rust https://fasterthanli.me/articles/working-with-strings-in-rus...
- cesarb 6y agoMost answers will focus on safety, but setting that aside, there's one thing Rust has which AFAIK C doesn't have: fat pointers. They're the implementation detail behind both array slices (keeping together the pointer to the first element and the length) and trait references (keeping together the pointer to the object and the pointer to the vtable).
- archon 6y agoPreface: This is an honest question, not an attempt to start a "which language is better" war. 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?
- emrah 6y agoRust is a systems (i.e. lower level) language similar to C and C++ that can be compiled to native standalone executables. 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-cplusplus-dev-time-to-do-some-rust https://fasterthanli.me/articles/i-am-a-java-csharp-c-or-cpl...
- oddx 6y agoPredictable (low) pauses. Ability to (easily) embed into other language/app as library/plugin.
- damnyou 6y agoControl over 95th+ percentile latency.
- dmitshur 6y agoFor anyone curious what a Go version of the same article would look like (as I was), I tried to answer that question by writing https://dmitri.shuralyov.com/blog/27 https://dmitri.shuralyov.com/blog/27.
- tsjq 6y agoThis is beautiful. Thanks for sharing. Pls post a separate thread (if not done already).
- faitswulff 6y agoI enjoyed this, thank you!
- walkingolof 6y agoComments like this are to far in-between on the internet, kudos!
- dnautics 6y agothanks for inspiring me, I did one for zig as well: https://gist.github.com/ityonemo/769532c2017ed9143f3571e5ac104e50 https://gist.github.com/ityonemo/769532c2017ed9143f3571e5ac1...
- sasindu 6y agoWas scrolling all the way for exactly this, thank you!
- mlthoughts2018 6y agoSo Rust is Scala but with some extra complicated additional syntax around borrowing references and generic lifetime constraints.
- steveklabnik 6y agoScala has many features Rust does not have as well.
- mlthoughts2018 6y agoYeah, when reading this I was wondering if Rust has sealed traits like Scala, and also structural typing. The extreme degree of shared syntax and shared semantics with Scala was really surprising to me.
- steveklabnik 6y agoRust does not have sealed traits, though you can sorta contort the privacy system to do similar things if you want. We also do not have structural typing. (Generally; tuples are structurally typed but nothing else is) A lot of Rust’s language people did a lot in Scala. The language’s are pretty different IMHO.
- nobleach 6y agoAs was explained to me, Rust has heritage from OCaml. If one squints, they can even see it still beneath the surface. I hear the original compiler was even written in OCaml.
- steveklabnik 6y agoYes, especially amongst the earliest folks, there was a lot of OCaml, and the original compiler was, yes.
- vips7L 6y agoProbably the reason why I don't like rust. Scala is hell for me. I've been burned by it so many times.
- techolic 6y agolet x; foobar(x); // error: borrow of possibly-uninitialized variable: `x` x = 42; possibly-uninitialized - Why does the compiler sound uncertain while emitting an error?
- steveklabnik 6y agoThe analysis is not perfect. It’s worded that way to acknowledge this fact. It also is language that works well when something may be initialized in some control flow paths but not all.
- aero-glide2 6y agoI had no intention of learning Rust, but this title just made me do that.
- nitred 6y agoAs a Python programmer with limited experience with compiled languages, Rust code was more intimidating to read or look at than C++, Java or Go. After only an hour, I am overwhelmed by the sheer beauty and mature design of this language - it almost reads like Python or as well as any compiled language can. I cannot believe that I am smitten by Rust within an hour. Its features seem, obvious. My experience with Go was frustrating since I felt like I had to give up elegance for practicality. I did not expect to learn 1-2% of Rust when I woke up today. My thanks to the author. I'm curious what other what other developers who primarily use Python think of this article and Rust in general?
- faitswulff 6y agoThis podcast might be relevant: the creator of Flask who is now using Rust: https://realpython.com/podcasts/rpp/18/ https://realpython.com/podcasts/rpp/18/ Edit - actually I was probably thinking of this podcast with the same interviewee: https://rustacean-station.org/episode/004-rust-in-production-armin-ronacher/ https://rustacean-station.org/episode/004-rust-in-production...
- nitred 6y agoJust started listenting to it. It's exactly what I was looking for, thank you. Armin Ronacher's opinion on such things would hold a lot weight in my head.
- artursapek 6y ago> I cannot believe that I am smitten by Rust within an hour 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.
- christiansakai 6y agoTry to use that in real world and see if your love still stays put. An hour is not enough to validate Rust.
- ibraheemdev 6y agoI was inspired by this article and wrote "Twenty minutes to learn Go" [0]. Go being a much simpler language than Rust, I feel that anyone who knows a programming language can become productive in Go in less than an hour. Of course this simplicity comes at the cost of increased boilerplate, less expressiveness... 0: https://ibraheem.ca/posts/go-in-twenty https://ibraheem.ca/posts/go-in-twenty
- freedomben 6y agoAbsolutely love the humor in this fn fair_dice_roll() -> i32 { 4 } :-D
- cesarb 6y agoIt's a xkcd reference. https://xkcd.com/221/ https://xkcd.com/221/ (xkcd: Random Number)
- kaleidawave 6y agoWas initially sceptical to this but after skimming think this is actually a very good introduction. I do like the brevity of it compared to the walls of text in the official rust one. Although this does give an illusion that Rust is very simple/easy to learn but any beginner will find that anything more than "Hello World" or "2 + 4" is 10x more difficult than writing in a interpreted language. Not because Rust syntax is difficult but the constraints it introduce require more thought of the design of the program. 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 :)
- fasterthanlime 6y agoSince a lot of folks take issue with the article's title, think of it as "If you had only a half hour to learn Rust, here's what I'd tell you". 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 :)
- runjake 6y agoI like to use LearnXInYMinutes as my first stop for learning a new language. 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://learnxinyminutes.com/ https://learnxinyminutes.com/
- moron4hire 6y agoVery nice. As a very experienced programmer who has now learned more languages than I can remember, I generally look for these kinds of cheatsheets whenever I'm learning a new language, followed by the official documentation. Other than that, I don't personally find tutorials very useful. 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.
- l00sed 6y agoI've mostly used web-specialized programming languages like JavaScript and PHP, and some Python. Some of the unique characteristics of Rust have been trickier for me to pick up. This looks like a fun and useful article, but I'd also recommend Rustlings to anyone interested in learning Rust. https://github.com/rust-lang/rustlings https://github.com/rust-lang/rustlings
- baby 6y agoUsually I would recommend learnXinYminutes.com for that
- akavel 6y agoNewbie question: in the last example: 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?
- Rotten194 6y agoIirc it’s moving the reference to answer, not the value.
- momothereal 6y agoIn this closure you are moving `answer`, that is, you are moving the reference itself into scope. The `challenge` reference is already owned by the closure since it's a parameter. The move doesn't mean the closure owns the underlying strings, but the references themselves.
- steveklabnik 6y agoI believe what happens here is that the closure tries to capture it as a &&str. This is because it defaults to trying to take the environment by reference. The "move" in this case means that it will try to take it by value instead. This feels tricky semantically because references are types too, so "taking it by value" means taking a &T rather than a &&T, just like you may think about how taking a T is by value as opposed to &T.
- ridiculous_fish 6y agoThis is confusing, and Rust's error messages make it much worse. If you try to remove the `move`, you get an error: > 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.
- dnautics 6y agoI spun up a roughly equivalent version of this for Zig, I would say this is about 70% of the language: https://gist.github.com/ityonemo/769532c2017ed9143f3571e5ac104e50 https://gist.github.com/ityonemo/769532c2017ed9143f3571e5ac1...
- infradig 6y agoNew to Rust, was excited to see Prolog anonymous variables make an appearance. But one thing struck me is the mismatch between variable and function declarations... 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.
- gusfrehse 6y agoThe way I see it, that would mean the function 'fair_dice' has type 'i32'. While in this case it maybe fine, if the function had arguments, it would be ambiguous.
- kag0 6y agoI thought the same. After how consistent Scala's syntax is, it's hard to adjust to what Rust has done here. In Scala val hello : String = "hello" // eagerly evaluated once def hello : String = "hello" // evaluated every time def hello(name: String) : String = s"hello $name" // parameters
- swsieber 6y agoWith type ascription being optional in some places, I have to wonder if using the colon for both type ascription and fn return type would introduce any parsing/grammar ambiguities. I 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.
- jtchang 6y agoThis article was excellent and will be saving it for the future when I'm ready to give rust a try.
- Havoc 6y agoI assume Rust doesn’t yet have a comparable library like pythons pipy yet? Ie everything imaginable covered.
- steveklabnik 6y agocrates.io has 52,000 crates. You may not find everything, but you can find a lot of things.
- Havoc 6y agoColour me impressed. Spot check on the python thing I build yesterday has an equivalent >A rust device driver for the Bosch BME280 temperature, humidity, and atmospheric pressure sensor and the Bosch BMP280 temperature, and atmospheric pressure sensor
- deepGem 6y agoIt's remarkable how similar Swift and Rust are w.r.t syntax. 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.
- Razengan 6y agoSwift tends to be a lot more readable with fewer ambiguities. Call me superficial but all the underscores and semicolons alone just feel like an eldritch summoning ritual in 2021.
- dalu 6y agoRust is a language that just doesn't go into my head. And whenever I have a question the community either downvotes or ignores me. The readability is bad. The error messages don't make sense. This type of post only covers the syntax basics. There's nowhere to turn to for applied concepts. 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.