Hey!

I'm a professional software engineer with several years of experience using Rust. Unfortunately I don't really have the time to contribute to Lemmy directly myself, but I love teaching other people Rust so if:

  • You are curious about Rust and why you should even learn it
  • You are trying to learn Rust but maybe having a hard time
  • You are wondering where to start
  • You ran into some specific issue

... or anything to do with Rust really, then feel free to ask in the comments or shoot me a PM 🙂

  • greyw0lv@lemmy.ml
    ·
    5 months ago

    I started learning rust yesterday, no specific questions, but the language feels weird to me. (background in java, c++, python)

    do you have sources i could read up on to get a thorough understanding. Books, news letters, websites etc?

    • SorteKanin@feddit.dk
      hexagon
      ·
      5 months ago

      C++ knowledge should make it easy to understand Rust. In a lot of ways, the Rust compiler is just enforcing all the stuff you need to do in C++ anyways in order to avoid undefined behaviour.

      I think The Book is fine, that's what I used to learn. You can also learn quite a bit by just reading the standard library documentation, which is very nicely structured.

  • maegul@lemmy.mlM
    ·
    edit-2
    5 months ago

    So far, I’m not sure I’m satisfied with whatever I've read about the borrow checker.

    Do you have any sort of synthesis of the core ideas or principles or best practices that work for you?

    Personally I’m partial to core or essential principles that seem esoteric at first glance but become clearer with more practice and experience.

    Otherwise, are there any pain points in getting better at rust that you think are worth just sort of not caring too much about and taking a short cut around until you get better? (Eg: just clone, don’t feel bad about it)


    Otherwise, thanks for this! Feel free to subscribe and chime in whenever people have questions.

    • SorteKanin@feddit.dk
      hexagon
      ·
      edit-2
      5 months ago

      Do you have any sort of synthesis of the core ideas or principles or best practices that work for you?

      I think it's hard to give some sort of master theorem because it really comes down to what you are doing.

      That said, start by considering ownership. As you start, avoid creating types with non-static references inside of them i.e. keep to types that own their contents. Types with references requires you to use lifetimes and you'll be better off getting used to that later. And frankly, it's often not necessary. The vast majority of the types you'll ever make will fully own their contents.

      Now when you make functions or methods, think of the three options you can use when taking parameters:

      1. Take ownership, i.e. MyType or self for methods. Use this if your function needs to own the data, often because it needs to take that data and put it into another value or otherwise consume it. Honestly this is the least common option! It's quite rare that you need to consume data and not let it be available to anyone else after the function call.
      2. Take a shared reference i.e. &MyType or &self for methods. Use this is your function only needs read access to the data. This is probably the most common case. For instance, say you need to parse some text into some structured type; you'd use &str because you just need to read the text, not modify it.
      3. Take a unique reference, i.e. &mut MyType or &mut self. You'll need this if you want to refer to some data that is owned elsewhere but that you need temporary exclusive (unique) access to, so that you can modify it. This is often used in methods to be able to modify private fields of self for example. You need to think about the fact that no one else can have a reference to the data at the same time though. Often this is not a problem, but sometimes you need to be able to mutate stuff from multiple different places. For that, you can consider either passing ownership around, for instance via channels and sending messages or you could reach for Arc<Mutex<T>> to allow mutation through shared references with a tiny bit of runtime performance cost.

      When you think in terms of ownership, the borrow checker becomes easy to understand. All it's doing is checking who owns what and who is borrowing what owned data from who and are they giving it back when they said they would?

      I hope that helps but again, it's a very general question. If you give me a concrete case I could also give more concrete advice.

      PS: Abso-fucking-lutely just clone and don't feel bad about it. Cloning is fine if you're not doing it in a hot loop or something. It's not a big deal. The only thing you need to consider is whether cloning is correct - i.e. is it okay for the original and the clone to diverge in the future and not be equal any more? Is it okay for there to be two of this value? If yes, then it's fine.

      • maegul@lemmy.mlM
        ·
        5 months ago

        This is actually a decent synthesis. I personally didn’t learn anything from it per se (not a criticism), but this sort of break down has been lacking from whatever I’ve consumed so far (mostly the Brown university version of the book) and I think it’s good and helpful.

        So far I’ve found the book (out the brown University version, because there are differences AFAICT) to be too front loaded on ownership.

      • maegul@lemmy.mlM
        ·
        5 months ago

        PS: Abso-fucking-lutely just clone and don’t feel bad about it. Cloning is fine if you’re not doing it in a hot loop or something. It’s not a big deal. The only thing you need to consider is whether cloning is correct - i.e. is it okay for the original and the clone to diverge in the future and not be equal any more? Is it okay for there to be two of this value? If yes, then it’s fine.

        Nice!

        I haven’t used clippy (just rust analyser so far, and the compiler of course) … but I wonder if it’d be nice to have some static analysis that gives some hints about how costly a clone is likely to be, just so you could have some confidence about not cloning where it will actually hurt.

        Also, thanks for the reply!

        • SorteKanin@feddit.dk
          hexagon
          ·
          5 months ago

          I would recommend changing rust-analyzer "check command" setting from "check" to "clippy", then you'll see clippy hints in your editor.

  • shapis@lemmy.ml
    ·
    5 months ago

    I'm halfway through the book and rustlings and it's... Awkward so far.

    Is it possible to become as productive with rust as one is with higher level languages?

    Or should I stick to gc languages for domains where gcs make sense.

    I was kinda hoping to make rust be my go to language for general purpose stuff.

    • SorteKanin@feddit.dk
      hexagon
      ·
      edit-2
      5 months ago

      Is it possible to become as productive with rust as one is with higher level languages?

      Definitely. Rust can be very high level, just as or at least very close to the level of languages like Python. Just as high level as Go or Java I would say.

      Rust is quite a wide language, in the sense that it is able to do both low-level and high-level programming. More generally, I'd say the distinction between "high level" and "low level" is just a matter of how much abstraction you use and you can build very powerful abstractions in Rust, and people have done this in many crates.

      For instance while using the axum web server framework, you might see code similar to this:

      async fn new(db: State<PgPool>, value: Json<MyType>) -> StatusCode {
          ...
      }
      

      This function defines a HTTP endpoint that takes a JSON body that deserializes to MyType and internally accesses a PostgreSQL database (for example to save the value in the database) and returns an empty body with a given status code. This is a very "dense" definition in the sense that a lot of semantics is pressed into so few lines of code. This is all possible due to the abstractions built by the axum web framework, and you see similar things in many other crates.

      I was kinda hoping to make rust be my go to language for general purpose stuff.

      It is a great language for all kinds of stuff - I use it as my general purpose language all the time :)

      I would encourage you to stick to it and see how the language feels once you try it a bit more in a real project, and not just in exercises. The book can be a little dry because it has to explain both the high level and low level features of Rust.

      If you have more specific questions about what exactly makes it awkward, maybe I can provide more guidance.

      • maegul@lemmy.mlM
        ·
        5 months ago

        General Purpose Language ...

        Interesting @shapis@lemmy.ml , I don't think I'd personally every thought of having rust as a go-to general purpose language instead of something higher level like python etc. I'd always presumed it'd be the tool for higher performance tasks/libraries when desired (where the enforcement of safety and the "work" necessary to "pass the compiler" and the type system are desirable features are, to me, desirable features).

        But so far, I've seen enough to appreciate how rust, once you know it and the packages/crates and std library, can feel kinda high level ... so an interesting prospect to watch out for.

        Exercises/Challenges to supplement "The Book" ...

        My personal experience with the book hasn't been fantastic. It's too dry and "academic" IMO and could really do with a more hands on hacking stuff together complementary book. Which is odd because it opens with a good example of just diving in and writing a small program.

        So yea, I'd echo SorteKanin's suggestion of writing programs as an exercise. I've tried to promote the idea in this community by posing challenges. I've got a "portal post" for them (only 1 so far) here: https://lemmy.ml/post/13418981. The first was writing a "file differ". I did it (you'll see the solution linked in the portal) ... it took longer than I'd preferred but definitely made me feel like I was learning way more than with the book.

        I have a strong feeling that doing more of that sort of thing, including Advent of Code, maybe euler problems (are they still cool?) or whatever else people are interested in (I'd like to have a shot at hacking together a basic web app) ... would be really helpful here (thoughts?).


        Tips on Rust as a General Purpose Langauge?

        @SorteKanin@feddit.dk ... do you have any thoughts to share on how Rust is best approached as a higher level / general purpose language? We discussed elsewhere in this comments section the idea that "over-optimising" memory management is unnecessary ... that outside of hot loops you should just happily clone variables to make the borrow checker happy. Any other tricks or approaches you can think of?

        Does unsafe mode become a tool worth using, or is it not worth the hassle? What about the Reference Counted pointer (smart pointer?) or Arc<Mutex>s (which I haven't come to learn/understand) for handling memory management?

        Are there good and nice crates or standard library tools that aren't the most efficient or idiomatic but good for just getting stuff done?

        Also, thanks for answering all of these questions!

        • SorteKanin@feddit.dk
          hexagon
          ·
          5 months ago

          do you have any thoughts to share on how Rust is best approached as a higher level / general purpose language? We discussed elsewhere in this comments section the idea that “over-optimising” memory management is unnecessary … that outside of hot loops you should just happily clone variables to make the borrow checker happy. Any other tricks or approaches you can think of?

          I would say make good use of the crates available. As said above, Rust as a language allows for very powerful abstractions. The language itself is quite low level, if you didn't have any other code to use. But the standard library alone gives you a lot of tools. Add to that a host of practical crates that raise the abstraction level and you've got a very high-level experience.

          I can't not share this meme btw. It's obviously a joke but every joke has a bit of truth:

          *removed externally hosted image*

          For instance, you've got anyhow that allows for a bit of "quick and dirty" error handling via the ? operator. It's useful for cases where you don't care too much about what error happens, just that it happens. And when you get an error, you get a nice explanation of what happened (no 100 line exception stack trace with 1 needle in the haystack that maybe tells you what went wrong).

          There's also serde (by the same author even) that allows for very easy serialization and deserialization, for instance into JSON or other formats.

          You could take a look at lib.rs to find more crates within a lot of different areas. It's a bit more categorized and better sorted than crates.io. Learning the ecosystem of crates and what's good for what is kind of a secondary thing to learn for Rust (or any language with a package ecosystem really) and it will take some trial and error probably.

          Does unsafe mode become a tool worth using, or is it not worth the hassle?

          No, unless you seriously need it and you definitely know what you're doing, you don't need it and you shouldn't need it. If you're reading stuff on this community, you don't need unsafe. I've worked with Rust for many years and I've still only used unsafe in the areas where it's really needed, like FFI (calling into C or C++ code). Perhaps with embedded programming you need it more, but most people don't do much embedded.

          What about the Reference Counted pointer (smart pointer?) or Arc<Mutex>s (which I haven’t come to learn/understand) for handling memory management?

          You should definitely learn about Arc (Atomic Reference Counted pointer) and Mutex (mutual exclusion lock) - I believe the book has a chapter or something about them. They provide one way to achieve "shared" ownership across different threads and you'll probably have lots of headaches if you don't know about them.

          Are there good and nice crates or standard library tools that aren’t the most efficient or idiomatic but good for just getting stuff done?

          There's some I mentioned above and for most major use cases, there are crates. Like axum for web servers as I mentioned above. Look at lib.rs I would say. It really depends on what specifically you want to do though.

  • thericcer@reddthat.com
    ·
    5 months ago

    I've been wanting to write rust for quite some time, but I can't get over crates. The system just seems insecure to me. What happens in 10 years when the servers go down? Is there any sort of mitigation for supply chain attacks? As I understand it anyone can submit code; what's stopping someone from putting malicious code into a crate I've been using?

    I suppose these are risks for any third party package system though.

    I've used Flutter infrequently and have experienced things like this with their package system.

    • SorteKanin@feddit.dk
      hexagon
      ·
      5 months ago

      I’ve been wanting to write rust for quite some time, but I can’t get over crates. The system just seems insecure to me.

      You're not the only one with this concern but it is essentially how modern package management works, not just for Rust but all modern programming languages.

      What happens in 10 years when the servers go down?

      While I don't think that would happen, there are ways to avoid this. You can host your own registry and mirror the crates.io crates, if you want.

      Is there any sort of mitigation for supply chain attacks?

      Whenever you have dependencies, you obviously need to either trust them or vet them. If the package is popular enough and the author is reliable enough, then you can choose to trust it. It really depends on what kind of risk you're willing to take on.

      As I understand it anyone can submit code; what’s stopping someone from putting malicious code into a crate I’ve been using?

      In principal nothing. Again, if you have dependencies, you need to vet them. This isn't really a Rust problem, it's just a general problem with depending on other people's code. You would still have this problem even if you manually downloaded external pieces of code from other people instead of via cargo.

      In practice, there is a team managing crates.io and I believe they do look for malware or malicious crates (like crates with names very similar to popular crates that attempt to trick people into downloading due to a typo in the name).

      But yes, this isn't really a problem with Rust specifically. I will say that the popular crates in the Rust ecosystem are generally very high quality and I have a fair bit of trust for them myself. Unless you are a big company that needs to carefully vet your dependencies, I wouldn't worry too much.

      • thericcer@reddthat.com
        ·
        5 months ago

        Thanks for your detailed input, I'm glad to hear that there is a team that does look out for things at crates.io, and that I can host my own registry.

  • z3rOR0ne@lemmy.ml
    ·
    5 months ago

    Great thread! Just subscribed to this c/

    Sorry I know its a few days old now, but I thought I'd just chime in and ask my question.

    First and foremost I'm a self taught web Dev(TypeScript, NodeJS, HTML, CSS), who has also done some small bit of learning C (built a basic UNIX shell and rebuilt some of the ls command in C) and done some shell scripting.

    I'm about half way through the Book and am also following along with a 9 hour long intro Video course from Free Code Camp where the instructor generally just has you go through practice.rs

    I'm mainly interested in using Rust as my go to back end language for HTTP/TCP servers and developing JSON and HTML APIs. Can you tell me which frameworks and crates/packages would be good for me to be aware of?

    I'm also interested in creating some CLI and TUI applications, so any frameworks/crates/packages I should be aware of in that realm you might recommend would also be greatly appreciated!

    Thanks so much. I got some great insights just by perusing this thread thus far!

    • SorteKanin@feddit.dk
      hexagon
      ·
      5 months ago

      I’m mainly interested in using Rust as my go to back end language for HTTP/TCP servers and developing JSON and HTML APIs. Can you tell me which frameworks and crates/packages would be good for me to be aware of?

      Look into axum. It's built on top of tower and tower-http, which is a general server/client framework. Axum makes it super easy to make HTTP servers, using either raw HTML or JSON. It has in-built functionality for JSON and if you want to do HTML you can reach for stuff like maud or askama.

      There's lot of crates around axum as well. You can try searching lib.rs which is a bit more nicely categorized than crates.io. For logging for example, look into tracing.

      I’m also interested in creating some CLI and TUI applications, so any frameworks/crates/packages I should be aware of in that realm you might recommend would also be greatly appreciated!

      For command-line arguments, use the derive functionality from clap. It lets you declare the arguments you want/need as a type and produces all the argument parsing logic for you.

      For TUI, I haven't tried it myself but I've heard that ratatui is good.

      • z3rOR0ne@lemmy.ml
        ·
        5 months ago

        Thanks so much! I'll be bookmarking these and checking them out as I go along.

        Lastly, I just wanted to ask a couple more questions if that's OK.

        How long did it take you before you started to become proficient enough in Rust that you could be productive for your employer? Were you already proficient in other systems level programming languages like C or C++ before learning Rust?

        Did you get hired as a Rust developer or were you working or your current employer utilizing another programming language and you eventually move to developing in Rust?

        Do you see there being more jobs utilizing Rust in the future?

        I know that's a lot, so if you don't want to field all of those, I understand, but I'm very curious so I thought I'd just put those out there.

        Thanks again!

        • SorteKanin@feddit.dk
          hexagon
          ·
          edit-2
          5 months ago

          How long did it take you before you started to become proficient enough in Rust that you could be productive for your employer?

          Not too long, around 3 months maybe. But it depends how much time you spend obviously. Learning the language is fairly quick. Learning the more exotic parts of the language took a bit longer but that's mostly cause I didn't need those things until later. Learning the package ecosystem is also something that can take a bit of research and you kinda have to just keep yourself up to date about cool crates via blog posts and sharing on online communities like this. But all this will probably depend on your prior expertise. I have a master's in computer science so it wasn't a huge deal for me.

          Were you already proficient in other systems level programming languages like C or C++ before learning Rust?

          I was... okay at C++ before-hand so kinda. But honestly C++ is such a shitty language that looking back I barely had any grasp at that time honestly. With Rust, it's so much easier and I understand how the system works so much better now, simply because Rust forces me to understand it. The compiler is a great teacher!

          Did you get hired as a Rust developer or were you working or your current employer utilizing another programming language and you eventually move to developing in Rust?

          I was not hired as a Rust developer. There was actually barely any Rust at the company when I joined. There were a few other colleagues interested in it and when I came in we really went for it. It took some convincing of management and stuff but now we use it in a lot of places and I write almost exclusively Rust at work.

          But I think I was very lucky in this aspect. There are few places where you will have such an opportunity to influence the technology in that way.

          Do you see there being more jobs utilizing Rust in the future?

          110%. Rust is set to replace languages like C and C++, and at the same time it is heavily competing with other programming languages. Even languages like Python. There's a huge opportunity to improve software reliability across the field with Rust.

          Rust is supported by the largest tech companies in the world and is getting integrated into Linux. There has not been a language with this level of dedication and support behind it for a long time.

          Growth is happening and it will only accelerate in the coming years. You can even see it happening on Google Trends. It's a great time to learn the language to get ahead of the curve!

          I know that’s a lot, so if you don’t want to field all of those, I understand, but I’m very curious so I thought I’d just put those out there.

          Hey I made this thread to answer questions, thank you for asking! I'm sure there are many lurkers who were also curious.

          • z3rOR0ne@lemmy.ml
            ·
            edit-2
            5 months ago

            Thanks so very much. Very informative and encouraging. As a mainly TypeScript developer whose only done some dabbing in C, bash, and python, I've been looking for a language that's a bit more abstracted than C, but not so pigeonholed into specific use cases like Golang (I'm still developing an opinion on Golang, not sure how I feel about it).

            Rust so far has appeared like quite a beautiful language and the compiler in particular is the best I've ever seen in terms of helpful error/warning messages!

            I'm sure I'll have my small complaints as I struggle to get good at Rust in the near future, but I think this is going to be my go to back end language for some time.

            I have plans to eventually convert the C code of the terminal based browser, links, to a Rust project to learn more about how a very basic browser is built. I'd also like to do the same for the TUI system monitoring tool btop, which is written in C++.

            I think just attempting those two "rewrite it in Rust" projects, once I have other smaller projects under my belt, will probably give me a good understanding not only of Rust, but also aspects of the HTTP/HTTPS protocols and systems programming not commonly encountered in the field of web development.

            Last question, I promise, lol. But what do you make of this plan? Are their any caveats or concerns I should be made aware of in regards to this endeavor?

            Again, thanks for everything!

            • SorteKanin@feddit.dk
              hexagon
              ·
              5 months ago

              (I’m still developing an opinion on Golang, not sure how I feel about it).

              I don't have concrete experience with Go but I've read enough about the language to form an armchair opinion. If you ask me, it seems pretty bad. It's like you just took C and you threw a garbage collector and an async runtime on top and called it a day. No lessons learned from any of the 40 years prior of programming language theory, just C with a garbage collector. I think the only reason anyone is using Go is because it's Google and they pushed it a lot. If someone made Go today and wasn't a billion-dollar corporation and tried to convince people to use it, nobody would use it.

              I have plans to eventually convert the C code of the terminal based browser, links, to a Rust project to learn more about how a very basic browser is built.

              I usually use reqwest for HTTP request stuff. But if your goal is to learn about more low level stuff, you might want to use a lower level library like hyper or even just only using the stuff in the standard library.

              I’d also like to do the same for the TUI system monitoring tool btop, which is written in C++.

              I'm a big fan of bottom, which is a TUI resource monitor. Maybe you'll get some inspiration from there.

              But what do you make of this plan? Are their any caveats or concerns I should be made aware of in regards to this endeavor?

              I can't really think of any problems. I think it sounds like a good idea to build some concrete stuff and see what you run into. Just realize that it might take a while before you get used to writing idiomatic Rust code, so don't expect your first project to be your prettiest work... 😅

              • z3rOR0ne@lemmy.ml
                ·
                edit-2
                5 months ago

                Definitely. Okay, that's about all I have to ask now. I'm bookmarking this thread though to refer back to. You've given me some great insights and resources, and have also pointed me in the right direction going forward.

                For now I'll be just making my way through the Book. I also have Programming Rust, by O'Reilly, Command Line Rust by O'Reilly, and Rust for Rustaceans to reference along with the plethora of online resources.

                I might PM you some time in the future (if that's okay) should I get stuck on something I can't figure out through the usual means (i.e. documentation, stack overflow, etc.).

                Again, can't thank you enough for the help. Cheers!

                • SorteKanin@feddit.dk
                  hexagon
                  ·
                  5 months ago

                  plethora of online resources

                  There's also zero2prod.com which is really nice as well. There's even a free sample of the book online.

                  I might PM you some time in the future (if that’s okay) should I get stuck on something I can’t figure out through the usual means (i.e. documentation, stack overflow, etc.).

                  Feel free to but also consider just posting a thread here so others can also see and learn 🙂. Just be sure to @ me to make sure I see it.

  • 1984@lemmy.today
    ·
    edit-2
    5 months ago

    I think its quite difficult to write Rust. I can get something working but any refactoring is a pain, and I usually get issues with the borrow checker as soon as I move things around.

    And it's complicated to get the lifetimes correct too. I feel like it's just a lot of effort, and not very fun to put so much time into figuring out Rust rather than what my program should do.

    But if I stick with it, it will probably become second nature. It's just a very annoying language sometimes because of the mental gymnastics.

    I switched to go and produced two full programs in a few weekends. It's just so much faster to write. Of course I could have bugs in those programs that Rust wouldn't allow. So I see the upside of Rust but it's just hard.

    • SorteKanin@feddit.dk
      hexagon
      ·
      edit-2
      5 months ago

      I usually get issues with the borrow checker as soon as I move things around.

      Once you get familiar with thinking in terms of the borrow checker (i.e. thinking in terms of how data can be safely accessed essentially), you'll be more at ease and you'll start building stuff from the start in ways that anticipate many of the issues you might run into. That's my experience at least.

      You "just" need to consider how you structure and access the data in your program. If you've used languages with garbage collectors a lot before, you're not used to thinking like that because the garbage collector just accepts whatever structure you give it and says "well I guess I'll have to make it work somehow, someway (with a lot of effort)".

      You'll find that once you structure your program in a way that the Rust compiler likes, it also becomes a lot easier to reason about it in general. A garbage collector won't "force" you to structure your program well in this way, which is why that kind of memory management often becomes messy when it scales to more than a few thousand lines of code.

      Just having the right editor setup and such can also help a lot for productivity.

      it’s complicated to get the lifetimes correct too

      Lifetimes is an advanced topic that you mostly don't need when you're starting out. It can often be avoided by sacrificing some small performance, for instance by cloning data. But lifetimes are also a very cool feature, it just takes a bit to understand it well. Once you get it, it's not so bad though.

      If you have any more specific questions about what you were trying to build or what errors you ran into, feel free to ask :)