12 ms·
Switching from C++ to Rust
- jesse__ 4y agoNice to see some level-headed anecdotes on the experiences of actually _using_ each language, as opposed to the usual "z0mg rustc fixez all yur mem0ry bUgz!!111one" And, as someone who's spelunking in the depths of a large CMake project right now, cargo sounds pretty nice.
- sophiabits 4y agoCargo is really nice! First party integration of developer tools is a big step forward and it’s nice to see it become more widespread (other examples include golang and Terraform) Bryan Cantrill has a number of talks about Rust which are similarly pragmatic
- paulddraper 4y agoRust advantages are one third memory safety, one third types, and one third package management.
- girvo 4y agoGosh I despise CMake. I despise it so much, I'm halfway through the process of extricating ESP-IDF from it.
- bluGill 4y agoI hate it too, but every alternative can't handle some dark corner of my build that just works in cmake.
- jesse__ 4y agoHave you tried just using bash? (not a joke) I do this for personal projects and honestly, considering the alternatives, I think it rules.
- bluGill 4y agoBash cannot handle figuring out all my dependencies and how to run them in across howeverany CPUs I have. Nor can it handle all the different cross compile, static analysis, address sanitizer, and so on.builds I run.
- dagmx 4y agoBash doesn’t scale unless you build out an entire system to make up for all the things cmake does for you, and keep it up to date. Need to handle creating projects for multiple ides? That’s a pain with bash unless you make an entire library of tools. Need to handle finding libraries with all their transitive dependencies? Another set of tools. At that point you’d just have reinvented cmake in a different language. Out of curiosity, are you using bash for projects that are limited to just yourself?
- delta_p_delta_x 4y agoI think the issue with CMake is exactly the issue with C++. There's a 'modern' way to do things, and a 'legacy' way to do things, and the respective designers of CMake and C++ have decided that it was—for several reasons—better to leave the 'legacy' stuff in the languages, rather than pull a Python and make a clean split. In 'modern' CMake, there are targets, and properties on said targets, i.e. compile and link options, C/C++ versions, libraries, headers, other custom dependencies, etc. There are also functions and generator expressions[1] to make control flow a little easier. On top of these, CMake's built-in `find-package` and `FetchContent` make package management a lot easier than it used to be. Want Boost? Just do `find_package(Boost)`, and then `target_link_libraries(<my_target> Boost::boost)`. It gets easier still with a proper C++ dependency manager like vcpkg or Conan. In legacy CMake, all these were set with global variables and there was no unified way to handle packages. I fully foresee going forward that at least a plurality of C++ developers will coalesce on a CMake + vcpkg (which has more packages than Conan) workflow. [1]: https://cmake.org/cmake/help/latest/manual/cmake-generator-expressions.7.html https://cmake.org/cmake/help/latest/manual/cmake-generator-e...
- jcranmer 4y agoCargo is definitely a more pleasant build system than anything the C/C++ world has, until you fall off the happy path. One of the pain points of trying to design a build system for C/C++ is that a lot of projects do weird stuff that needs to be supported in build systems, which means you end up needing escape hatches to do that weird stuff all over the place. Cargo takes a narrower view, which means it doesn't attempt to do things like package things for install or handle multi-stage builds. It also has the advantage that things like running tests or package dependencies were built in from the start, so it doesn't have to try to support a million different tools that provide that functionality.
- pornel 4y agoI think Cargo is more of a social success than a technical one. People just agreed to use one standard tool, and that does wonders. Technically nothing stops C++ from having the same, except getting everyone to agree on one tool.
- burntsushi 4y agoThe call out to sum types is something I feel. I've been using Rust daily for almost 10 years now, and sum types are absolutely still one of the things I love most about it. It's easily one of the things I miss the most in other languages that don't have them. I'm usually a proponent of "using languages as they're intended," but I missed exhaustiveness checking so much that I ported a version of it to Go[1] as a sort of lint. [1]: https://github.com/BurntSushi/go-sumtype https://github.com/BurntSushi/go-sumtype
- zabzonk 4y agoso, um, unions? i have to say that in many years of programming, i have almost never needed to use such types.
- nicoburns 4y agoDoes your code ever contain class hierarchies with a fixed set of classes? Or variables where certain values have special case meaning? Those are the cases where Sum Types make things immeasurably nicer than the alternatives.
- zabzonk 4y ago> Does your code ever contain class hierarchies with a fixed set of classes? no - one of the advantages of OO programing is that class hierarchies (should you feel the need to use them, which mostly i do not) can be expanded. or indeed contracted. > Or variables where certain values have special case meaning? very, very rarely (i would say never, in my own code) but of course we have the null pointer as a counter-example. to which i can say: don't use raw pointers.
- pclmulqdq 4y agoI didn't know Vatic Labs was a Rust shop! (I joke, but they are a finance firm that is notoriously paranoid about you announcing where you work). I'm glad to hear about your experience with the language as a developer. It's also been my experience that Rust has the magical power where your compile errors are almost always logic bugs. That's pretty cool from a psychological perspective, because you really feel like your C++ compiler is your enemy (or worse, your lawyer) while the Rust compiler is your friend. The C++ developer experience is absolutely horrendous (with far too much of the unholiness that is cmake), and I hope that shedding some light on the situation can help people understand how to make it better.
- xiphias2 4y agoThe most fun thing reading this comparision is again that for an experienced C++ programmer who is used to managing memory by hand (and fixing segfaults), Rust's memory model doesn't seem that hard, because it makes sense, and he understands why the checks are important.
- charcircuit 4y agoRust's memory model is even more familiar to C++ programmers who don't manage memory by hand because they have the same concepts of borrowing and lifetimes.
- est31 4y agoYou are still "managing" it even in that instance (just like in Rust). The overhead is just smaller than in say C or old style C++ with new/delete.
- staunton 4y agoThe overhead is the same. Rust just takes care that you're doing it right, while C++ lets you shoot your foot off in this area.
- kitkat_new 4y agonot only the overhead, but even the semantics The difference is that the use of the smart pointers is checked of the compiler
- ryandrake 4y agoI know this is an unpopular opinion but if you want to stick with C++, the solution to this, at least in my experience, is to stop doing things that let you shoot your foot off. C++ gives you every tool in the tool chest, and most of them are not safe. Stick to a safe subset and you've solved 90% of all those stereotypically C++ problems. I've got a pretty big C++ codebase for my hobby projects, sanded down, polished and perfected over the years without the usual corporate pressure to ship. The few times I run into memory corruption, a memory leak, a segfault, dereferencing a shit pointer, undefined behavior, and so on, its always, always because I'm doing something I shouldn't be doing. Like working with raw pointers or pointers to pointers to pointers, or traversing an array of bytes to do something there's already a library that does, or manually calling delete on something, or using reinterpret_cast<>, or using one of the many footguns C++ happily gives me. The simple key is to just stop doing these unnecessary things.
- eminence32 4y ago> What kind of C++ and Rust? I appreciate the inclusion of this section. Different people writing C++ can have wildly different experiences, based on the type of things they are working on. This section offers a good reminder about this, and that one person's perspective is not more or less correct than anyone else's.
- ridiculous_fish 4y ago> How these commands change if I want to build the project with sanitizers? What do you mean the sanitizers are not supported by the build process? Why the build script suddenly started printing linker errors? Doesn't Rust require you to switch to nightly to use sanitizers?
- girvo 4y agoI want to switch to Rust, to get away from the C/C++/Nim mix we rely on at work. But embedded development (specifically for the ESP32-S3 chip, but we also have to do a lot of STM32 work as well for our coprocessors) has sort of forced us down this path. That said, the bulk of our code is Nim, and it is lovely to work in. I just wish we didn't have to rely on C/C++ libraries and toolchains as much. CMake will be the death of me, I swear, and it would be nice to have all the thought we have to put into to lifetimes and safe bindings around unsafe C calls be able to be encoded into the language itself, rather than as comments and so on.
- jamesmunns 4y agoFor what it's worth, the entire esp32 family is officially supported in Rust by espressif themselves [1], and the stm32 family is probably one of the most widely used cortex-m families in embedded Rust as well[2]. [1]: https://github.com/esp-rs https://github.com/esp-rs [2]: https://github.com/stm32-rs https://github.com/stm32-rs
- girvo 4y agoRight, though Espressif's official support for anything should be taken somewhat with a grain of salt ;) Having used their tools at work in anger for years at this point, there is a lot of gotchas, issues and bugs with their bindings at this point -- not all of which is Rust's fault, but the underlying problems with ESP-IDF itself. That said, its getting better over time, so I'm keeping a close eye on it (and we keep some experimental projects up to test it every couple of months). The upside of Nim is that "it's just C" at the end, with all the upsides and downsides that comes with. I'm very hopeful though! Edit to add: We started this project quite a while ago, too, which forced our hands. Writing unsafe Rust is a pain, so I didn't want to take the burden on for managing bindings myself at the start. If we were to start again, maybe we'd have made a different choice, but Nim at least eased the pain quite a bit.
- n8henrie 4y agoDoesn't the ESP32C3 have native rust support -- no esp-idf or espressif official support concerns need apply? Are you stuck on the S3 exclusively?
- epage 4y agoBackground: C++ since around 1998, added in Python around 2008, Rust around 2016 While I agree with everything in the article, some times I wish I could have it both ways with: > First of all, generics without duck typing are greatly appreciated. Traits clearly indicate the contract struct or function expects from the type, which is great. This also helps compiler to generate helpful error messages. Instead of “invalid reference to method clone() on line Y” you get “type X does not implement Clone” - clean and informative. I will say that there are times when I wish I could sneak in some duck typed traits, particularly `Debug`. Sometimes you are working in generic or dynamic dispatch code and just want to use `dbg!` but can't because (1) you didn't think ahead or were too lazy to annotate things with `Debug`, (2) you are a bit paranoid about excluding a type that doesn't support `Debug`, or (3) You are doing dynamic dispatch and `FooTrait + Debug` only works for generics. `Debug` is also just one example. Overall, I love the explicitness but at times I do wish I could fudge things a little.
- tialaramex 4y agoI strongly recommend just writing a #[derive] line for every user defined type you make. Start off with Debug in there, and you'll find often you already know some other traits that'll be trivially derived for this type, Clone, Default, stuff like that.
- epage 4y agoGenerally I do. My comment isn't about whether my own types are `Debug` but others on top of several other problems.
- gpderetta 4y agoThe original C++0x concept proposal had concept checking, but had an escape hatch to instantiation-only checking when needed.
- unwrap_abuse 4y agoSo the problem with rust you will find is the abuse of unwrap in ecosystem, so your code will need to be panic-safe. We wanted to get rid of C++ exceptions but traded it for panic hell.
- celeritascelery 4y agoAn important distinction is that rust doesn’t use exceptions for recoverable errors. You don’t have try/catch like you do in C++. Instead you use the Result type to propagate errors. This has the advantage of avoiding many of the downsides of exceptions (like leaving your program in a bad state) while making error handling more explicit.
- Rusky 4y agoThis doesn't mean you don't still have to be panic-safe, though. This is mainly important for unsafe code, because it has to preserve memory safety even in the presence of panics. But it can also be important for safe code in an application that recovers from panics.
- celeritascelery 4y agoYou are correct that there are circumstances where you have to consider panic safety. But those are rare. Most code is not unsafe, and catching panics is usually bad practice in Rust (though I am sure there are circumstances where it is needed). In C++ by contrast you have to think about panic safety almost everywhere. Rust’s error handling is a big improvement in that regard.
- blub 4y agoRust programmers misuse unwrap and the like all the time, to the point that I’ve seen some projects explicitly state that they don’t do that, since nobody wants their library to crash their program because someone was too lazy to propagate errors. Which brings me to the point: propagating errors is tedious enough that people are looking for shortcuts, which then cause other problems.
- jhatemyjob 4y ago[flagged]
- burntsushi 4y ago> C++ has a very long history (over 50 years) and to say he's some expert matter on the subject after a mere 4 years of "professional experience" is quite baffling to me. It's understandable that you're baffled, especially given that the OP didn't claim to be an expert. The OP pretty clearly did not claim any authority, and instead went out of their way to clearly disclose not just the number of years of experience they have, but what they worked on. > Waste of time It's worse than a waste of time. Comments like yours make HN a worse place. Extrapolating some minor English writting buugs intto an asessment on how good they're code is? Man, what an absolute stinky pile of bullshit.
- wiz21c 4y ago> Man, what an absolute stinky pile of bullshit. Now let's feed that as a prompt to DALL-E :-)
- aldanor 4y agoThe username checks out.
- jnwatson 4y agoHe didn't claim expertise. It is actually more interesting to me to hear someone's opinion with a medium level of expertise in the language. We've had plenty of experts and beginners already weigh in. English isn't a first language for everyone. Sounds like you need a break.
- Snelius 4y agoGood luck! lol
- alphanullmeric 4y agoRust will only be a real competitor once it’s generics can hold a candle to C++ templates.
- School-Cotton 4y agoI disagree, Rust is already being used for tons of real-world projects. It’s quite rare that you miss the flexibility of templates (and can’t accomplish a similar thing using macros or generated code).
- pie_flavor 4y agoThe article specifically mentions not holding said candle as a positive. I would too. They're confusing at best and undebuggable at worst, and virtually everything you can do with them that you can't do with generics is something it'd be better for everyone if you didn't do.
- alphanullmeric 4y agoOh here we go again. “Everything rust can’t do is an antipattern” is not a valid argument. Tuples for instance are a library feature in C++ but have to be a language feature in rust. Plenty of other useful things that C++ can do and rust cannot. https://youtu.be/gOdcNko2xc8 https://youtu.be/gOdcNko2xc8 https://youtu.be/tiAVWcjIF6o https://youtu.be/tiAVWcjIF6o
- deleted 4y ago[deleted]
- pie_flavor 4y agoSo, in response to 'templates are generics + things you shouldn't do', your counterargument is a non sequitur about tuples, a video titled 'Code You Should Learn From & Never Write', and a video about introductory templates which doesn't actually contain any counterexamples?
- aldanor 4y agoYou forgot to add /s. Thanks but no, replacing a bunch of code as strings and then relying on some code _not_ compiling should be left in 20th century for good.
- lenkite 4y ago"First of all, generics without duck typing are greatly appreciated." Err..C++ has concepts. No duck typing required.
- mlindner 4y agoOnly C++20 has concepts, which is a lot newer than Rust is. I've yet to ever see a C++20 concept in the wild or anyone using one outside of an example. Heck, if you ask the average C++ programmer about concepts they'll likely have not even heard of them.
- Kranar 4y agoErr... C++20 added concepts but not definition checking, so templates are still duck typed. That is, it is still possible for a substitution failure to occur after performing a concept check. Definition checking would eliminate such failures. In every language that I can think of that supports generic programming (including Go), there's support for definition checking.
- up2isomorphism 4y agoEssentially, this tells that: 1. how much psychological trauma it brings to average developer because today's most C/C++ library is not shipping static library by default. 2. how much pain it causes when the build system just can not copy the whole damn library into somewhere called lib and include instead spill into hundreds of random locations even we know that it will just build if we just copy it one place. 3. returning a struct with a integer status in it is so challenging for average programmers. All these must be true because it seems it is the reality.
- brokenpipes 4y agoThe author mentioned that Rust errors sometimes force you to restructure your code to satisfy the borrow checker. I’m curious whether anyone has some real-world before-and-after examples of this kind of change.
- phamilton 4y agoA very specific case on admittedly a toy project. I was working on a card game simulator and I had a Vec of players. I needed to pull two players from that Vec and the first player would give a card to the second player. In my head I would grab both players via get_mut and then perform my operation. However, get_mut borrows the vec mutable and the compiler complained that I borrowed the Vec mutably two times. It took me a bit to understand why the compiler complained, but then it clicked: It couldn't prove that get_mut wasn't returning the same item both times. There were a few solutions. One was to borrow the first player, take a card, drop the &mut and then take the second player. At some point in the future I could use https://github.com/rust-lang/rust/issues/104642 https://github.com/rust-lang/rust/issues/104642 to get_many_mut. I ended up with a pretty inefficient version of get_many_mut that fully traversed my iterator to get the two mut references (which works because traversing the iterator guarantees you won't see the same element twice) and it was fine for a collection of a half dozen players. Anyway, there's a little example. Anyway, it was a small thing but
- pie_flavor 4y agoThe most common example is when you accidentally start doing object-orientation, and are trying to get a value to hold a reference to another value when there's no point in doing so from an ownership perspective, just so that it can be part of `self` in the method. The more you try to preserve the model, the wackier the errors get, until one of them is literally unsolvable and you have to junk the object-oriented design entirely. Generally this happens a maximum of twice, because once you've learned it your reflexes change, but generally this happens to everyone who came from an object-oriented language.
- berkes 4y agoI come from OOP languages and do rust mostly nowadays. > you have to junk the object-oriented design entirely I think it's not this black-and-white. OOP on a higher level is about encapsulation and message passing. Such design is perfectly doable in Rust. I'd say that it's more natural in Rust due to it's `impl` concept: where behaviour and data are coupled in a way that's different from most OOP languages. Who owns which data, and who can operate on it, is something that, in OOP, should be thought about just as well. Java, Ruby, et al make it easy to make a mess from this; yet that doesn't make all OO-design a mess. Ihat really is "bad use of OOP", and no reason to "junk the OO design entirely". At most it's "junk the bad OO design".
- chombier 4y agoTo me, one of the best thing in Rust compared to C++ is that I no longer have to be super careful all the time to avoid common pitfalls, I just write stuff and fix compilation warnings/errors until the compiler is happy, and things mostly just work (apart from domain-specific bugs of course) After getting used to the basics of Rust, I found the cognitive load to become much lower compared to C++. There's just no way I could write correct C++ code in such a careless fashion. So now I can spend brain cycles on things that actually matter, and it's great.
- tommiegannert 4y ago> In C++, you can comfortably measure the size of error messages in kilobytes. Infinite scroll in the terminal emulator is an absolute must because oh boy does the compiler like printing text. And you usually want the first line, because that's where the line number you actually want to go to is. Perhaps removing repetition and not printing lines of stdlib headers would help.
- IYasha 4y ago> I feel more at piece shipping Rust code that C++ code. More a piece? More in pieces? :D I too got lots of crashes and UB in my life, but more because of pile-of-garbage architecture and interoperability than of language. (un)surprisingly, Rust emerged AFTER people learned their mistakes in C/C++ so it gets lots of attention and expectations.
- deleted 4y ago[deleted]
- hollowonepl 4y agoI read the article only not to be able to to find any meaningful notes. I did not expect versus so I support the writer that it's weak point to compare on the versus basis, but still as a person who actively maintains C++ experience since 1996 and been through Borland, Watcom, Visual C, old standards, C++11, C++14, and tries to follow isocpp.org standard discussions to understand where C++ is heading as standard and still use clang, cl and gcc regularly and.. I have zero experience in RUST, I only heard from many seasoned C++ developers that this platform comes with significant value proposition. I had no chance to meet it yet, nor I have currently time to experiment, thus I was curious about the article to help me understand the differences. The only thing I remembered from the article is that compiler error messaging are different in the two and more clearly defined in RUST. Plus classical anti C++ example => memory management. C#, Java already addressed that, so I expect RUST has something more unique than that. Can somebody point to better article that shows some practical appliances why to switch to RUST if you have significant C++ experience? Not that I want to bitch the author. Nice try explaining something, bue you know fixing error messages in C++ code was never a random staring at the code in my case.
- deleted 4y ago[deleted]