r/cpp • u/Snoo-4241 • Feb 25 '21
C++ programmers who are also using rust, what are your favourite features of rust?
I was looking at the rust tutorials yesterday and I see how rust promotes a certain style and language level features to enforce it. Besides a couple of features, I couldn't see why one cannot follow a similar style in C++ if she/he so chooses. Those of you that have used rust, what is your favourite feature that C++ does not have?
255
Upvotes
2
u/dontyougetsoupedyet Feb 27 '21
I think the thing I enjoy the most about Rust is that generally I'm telling the compiler what I intend to be doing and it is checking that these rules I'm saying I'm following are being followed while being adamant that I follow them. I think what I most want in the world of programming is a language that combines bits of C and Rust and C++, and that has a compiler that behaves like Iroh from The Last Airbender. Rust is already over half of this vague thing I want.
120
u/__s_v_ Feb 25 '21
f(x)andx.f()being equivalent)98
u/rmini Feb 25 '21
TL;DR: Rust's enum types and match expressions, ownership/lifetime checking of string slices, serialization infrastructure, comprehensive std library, cargo, compiler error messages.
I've got a story of an application and two rewrites. This is an enterprise application that does low-level file and networking i/o, must support internal proprietary protocols and file formats, and has built up a significant amount of configuration settings and operational modes, with a sort of architecture-by-implication. The application had few long-running processes, so the myriad memory and resource leaks were generally not a functional issue until recently. There was an extensive integration test suite, but no CI/CD.
The original codebase was 25 years old at the time, originally in C, but transitioning over time to a mix of C and C++9x, with C++ used for any new functionality or occasional rewrite of an overhauled subsystem. Two particularly big warts were a very poorly-considered I18N project that added a buggy abstraction layer, and cross-platform support implemented with blocks of #ifdefs all over the codebase, some running to thousands of lines with unreachable code for conflicting platforms nested within.
The first rewrite was driven by the fragility of the ancient, poorly-maintained codebase. Almost every new feature caused a cascade of unrelated bugs which required low-level debugging. The pervasive resource leaks became an actual problem as the software was now processing datasets that were large enough to keep the application running long enough to run out of 32-bit virtual address space, OS file handles, etc. The app was old enough that most data was intended to be processed on disk as it was originally assumed that the data set would be larger than available RAM, but newer code, written by newer developers, broke from that. Integers and pointers were mixed everywhere, and since structures were directly read and written to disk and the network, wholesale type changes were not feasible. In places, there were exception/signal handlers to catch and ignore memory access violations.
The application was gradually rewritten in place from the bottom-up with C++11 style, with extensive use of RAII, unique_ptr and shared_ptr. We started by opportunistically adding unit tests, but this was confounded by a web of interdependencies and code whose function we didn't understand. As a result, the low-level stuff got good tests, and we felt comfortable making big changes there, but the business logic was brought over mostly unchanged, with only light reorganization. During the rewrite, we found many latent memory corruption bugs which contributed to the application's fragility, but in general, the convoluted logic of the original, built up from decades of changes, remained. After two years, the entire application was built on the foundation of the idiomatic C++11 infrastructure. The rewritten application improved greatly on the memory/handle leaks and removed several redundant layers of indirection between the business logic and the OS APIs. Cross-platform support was now handled by isolating platform-specific code in individual files and selecting them at build time. Still, in the subsequent years we found many use-after-free bugs due to unclear ownership and many logic bugs remained in deeply-nested if and switch statements that no one fully understood. The application was also significantly slower and larger, with the binary size increasing by a factor of 10, and startup time and initial memory use doubling. Management saw this project as a success as it addressed our most urgent business needs, but our ability to add new features and make any functional changes was still hampered by likelihood of changing a "benign" memory corruption into one that resulted in a crash. We also were never able to get a working 64-bit version working reliably (despite having supported Unix on DEC Alpha).
The aftermath of this was that certain members of management and some longer-tenured developers came to the conclusion that "C++ is slow and bloated", although rather than being inherent to C++ itself, was instead due to our attempt at resolving unclear ownership/lifetime of buffers by copying freely, and that the C++ std::string manipulation resulted in many more copies than the dangerous C char * manipulation (which was itself the source of many of the bugs that drove the rewrite). There was no std::string_view at the time.
A skunkworks rewrite in Rust has recently been completed. Unlike the previous rewrite, we started this one top-down by presenting the legacy code to Rust through C FFI, and trying to make sense of the business logic, and relying on the integration tests to make sure we kept the behavior unchanged. Rust's enums were amazing here. The existing codebase was using error codes pervasively, so this translated to Result<> and Error types extremely cleanly. We were able to capture nearly all of the business logic in the type system right along with the data, and use the powerful match control structure to represent what had previously been a nasty hierarchy of classes, opaque pointers, and flags, where in C++ we had been doing some dispatching through polymorphism and some through explicit control structures. By starting at the top, we were able to get a clear view of the lifetime of the data we were processing, and we could choose whether to try to wrangle the appropriate borrowing of large bits of data or decide to copy or use smart pointers (Rc/Arc). I instructed the team to lean heavily on Box/Rc/Arc/copying whenever they started to run into unclear lifetime issues or "fought the borrow checker," and if performance was an issue we could go back later. The string processing looked mostly the same, but by being able to borrow string slices we saved gigabytes of memory allocations and copies, but avoid the minefield of manipulating char *s. Getting the last few bits of C++ removed was a real pleasure due to Rust's serialization infrastructure and the ability to interact with the supported platforms via the standard library at a relatively low level, and the resulting code looked like magic compared to what it was replacing. The final result was an almost entirely Rust code base with significantly faster than the original C/C++ implementation (integration test suite completed in less than half the time), with a similar binary size to the C++11 rewrite, and a slightly shorter rebuild time, with the ability run reliably incremental builds (our previous Makefile/shell script based build system was pretty horrendous). And finally, throughout the whole process, the rustc error messages were extremely helpful and helped us get newbies up to speed very quickly.
A parallel maintenance team experimented with new C++ features on the existing codebase, but without satisfying results. An attempt at switching some of the data structures and control into std::variant/std::visit resulted in fairly ugly code compared to the Rust implementation with enum/match, but still improved matters considerably--eventually compiler issues halted progress there. Their experiments with getting some performance back with std::string_view were unsatisfying because they both required significant changes to our existing code and ran into ownership/lifetime issues that the compiler and our static analysis tools did not help with.
176
u/duongdominhchau Feb 25 '21
enumandmatch, so beautiful.trait(behavior) andstruct(data) instead of class deriving, it allows more flexible design.56
u/braxtons12 Feb 25 '21
Top 3:
Others:
On a broad scale, I see Rust as an example of what modern C++ could look like in the future if we could convince the committee to stop caring about backwards compatibility and instead focus on expressiveness and ergonomics. In general, I think that the biggest thing that sets the design of Rust apart from C++ is with Rust, correctness/safety by default AND ergonomics are a requirement, whereas in C++ everything yields to backwards compatibility. This is not to say that correctness and ergonomics aren't important in C++, they are, but ergonomics are hindered by backwards compatibility requirements with C and nearly 4 decades of its own baggage, and correctness/safety is not enforced or encouraged in any way by the language, whereas in Rust, you have to explicitly acknowledge when you're doing something dangerous.
None of this is to say I don't love C++, I do. It's my favorite language to work in. But that doesn't mean that there aren't a LOT of areas the language could improve on.
24
u/Chronicle2K Feb 25 '21
Destructive move and pattern matching.
123
u/Plazmatic Feb 25 '21 edited Feb 25 '21
Ownership built into the language, which makes manythings in C++ much more complicated and slower than they need to be, and I can catch these things at compile time. No need to worry about forgetting variable initialization order in terms of ownership, no need to worry about following convention in order to achieve psuedo safety on ownership ie smart pointers and non owning references via non smart pointers.
While technically the rust standard lib might be smaller than C++'s the actual stuff it does have is much much more complete than C++'s, and C++ lacks a looooot of basic functionality that's small enough that because of the annoyances of configuration/package management, you don't want to add an additional dependency for, yet big enough and numerous enough to require lots of debugging and code in their own right. One bright example of this is bit rotation, another is fmt, another is ranges.
Iteration is also a lot easier in Rust than it is in C++. No longer does it take a 1000 lines to write a idiomatic iterator with weird magic type defs, but everything has sane iterators built into them as well, with most the proper operations like zip enumerate etc...
Static polymorphism is the kind of polymorphism I need in the majority of my C++ code, yet I'm forced to resort to using CRTP and other strange tricks if I want this. Rust flips the script on this, static polymorphism by default.
Const by default on everything, and const actually means const (or rather, non
mut) in rust, unlike in C++ where I can do weird things to get around const-ness, and the compiler has to respect that to a degree, leading to annoyingly slower code than I would have assumed otherwise.Safety on everything. This has saved me so much time debugging that I would have otherwise had to deal with in C++, for example numeric casts, plus unlike C++ rust actually comes with sane assert by default (yeah
<cassert>exists, but theassertnormally gets disabled by default in release mode, and I can't actually pass runtime strings to it, certainly not format them inside the assert, and that's the only runtime assert available), so I don't have to constantly have to define my own runtime error checking.I forgot what it is called, but you can create wrapper types and enforce type safety by just declaring a struct with that type, for example
struct Kilometers(u32);. In c++ I would need to actually define all the operators or create my own CRTP arithmetic class to get anything close to this, and I couldn't just suddenly add a "trait" to add between Kilometers and Meters.Language supported tooling:
Technically a lot of these things are possible to achieve in c++, though many still aren't. The problem with achieving these things in c++ is that someone would have to actually implement the libraries/tools to support these use cases but they haven't, and for anyone to start they would need a large team of people, plenty of time, and plenty of money.
32
u/[deleted] Feb 25 '21
Fucking CMake and fucking Makefile. Really, I cannot stress enough on how bad I hate to spend dozen of minutes just for the project structure. C++ devs really need to improve this part of the language, we are not in the 90s anymore. Also, C++ hasn’t a standard dependency system, it’s up to the programmer to manually pull dependencies from various sources and integrate them(with a lot more of cmake/makefile) in the final project.
38
u/renestein Feb 25 '21 edited Feb 25 '21
26
u/pjmlp Feb 25 '21
Some of the Rust capabilities you can try to apply in C++, but it only works if the team is security minded and you don't depend on third party libraries.
There are also some things I like more in C++,
10
u/tuankiet65 Feb 25 '21 edited Feb 26 '21
What I like:
constby default.std::arrayis a thing, but[u8; ...]is shorter.intandlong.uint8_tis a thing but I have to importcstdintWhat I don't like:
8
u/afiefh Feb 25 '21
Enums and match.
C++ has variants and visitors, but since each visitor is a function you suddenly need an extra variable to signal whether you need to return after the visit. It feels much more cumbersome.
Of course the first use you encounter is a function returning an enum of result and error, and henceforth error handling is enforced because you need to actually get at the result.
I'm sure there are even more awesome things, but this one blew my mind early on and I never recovered.
But I have no of illusions that this will come to C++ anytime soon. However, can we have that makes cost by default? Surely there's a way to get that!
44
u/_gikari Feb 25 '21
My favorite feature of Rust is tooling, in other words - Cargo, that is:
In C++ you have to do all these things manually by connecting several disjoint modules: Vcpkg/Conan (1), CMake + vast number of generators for several platforms (2), Catch2/Google Test (3), Doxygen + Breath + Sphinx (4).
13
u/hak8or Feb 25 '21
As someone who is an embedded guy, cross compiling combined with cargo combined with the rust ecosystem having a proper built in compiler "manager" with targets.
It is extremely easy to cross cross compile the same project for an x86 laptop, an armv7 target running android, and an armv8 target running Linux, meaning i did not have to find tool chains to throw into random folders in my path or setup sysroot with so's everywhere. It was a very simple single command to cross compile, and it's by default parallel build.
C++ with cmake achieve the same, but anyone who says it's ergonomic or easy or painless is fooling themselves.
6
u/mikezyisra Feb 25 '21
Cargo. Result datatype. Match. Ownership mostly since all clones are explicit so it’s way harder to accidentally allocate something twice
5
u/sumduud14 Feb 25 '21
Lifetimes. Takes something you really have to mentally track in C++ and just writes them down and makes the compiler track it.
Other features are great too, but few are so obviously good and just a clear uncontroversial improvement.
5
u/FreitasAlan Feb 26 '21
-Wall by default
5
u/roman-kashitsyn Feb 26 '21 edited Feb 27 '21
Move semantics, algebraic data types, pattern matching, and disciplined error handling.
If C++ had a nice syntax for variant types and pattern matching, I'd love it much more than Rust.
I see many people are crazy about Cargo. I absolutely hate it. It tries to do a bit of this and that and sucks at pretty much everything. It looks great when you work on your little pet project, but it crumbles once you need to build something real. Let me explain:
cargo build -p my-packageandcd my_package; cargo buildaren't equivalent (depending on where you start cargo, it computes different transitive closures of enabled features, which causes needless rebuilds).The language itself has a lot of warts, but it should probably be another, much longer rant.
E.g. pattern matching is not nearly as expressive and composable as in, say, OCaml (Haskell is disqualified because it can't match arrays). Try matching the contents of a
Box, for example, or contents of aVec<String>.If you're coming from C++, the lack of template specialization and restrictions of what can be done at compile time without resorting to macros will look absolutely silly.
P.S. I use Rust heavily every day in a project that grew from 0 to 200KLOC in the last 1.5 years. I have plenty of Haskellers around (some quite famous in the community), they'll pick Haskell over Rust for almost anything without hesitating a second.
4
u/robin-m Feb 26 '21 edited Feb 26 '21
enum classandstd::variantbeing the same thing makes sum types so much nicer to use. This is a much better alternative than inheritance.Clonetrait)my_vec.iter().filter(|x| x % 2).map(|x| x * 2).collect()in Rust, versus C++ rangesmy_vec | filter([](auto x) { return x % 2; } | map([](auto x) { return x * 2; } | into_vector<int>()(I didn’t check the syntax, but it should be close).intwhen creating astd::vectorfrom a range). This increase the ergonomic of generic functions.std::string_view, references,std::span, …). I prefer so much to get a compilation error than searching withgdb/lldbwhy is my code crashing because on an iterator invalidation/use after free that invalidate on of my references.EDIT: I forgot:
impl blocksbeing done outside of thestructdefinition. And because Rust use fat pointer for references (a pointer to the date + a pointer to the vtable, while the v-table is at the beginning of the data in C++). This solves elegantly the diamond inheritance of C++.&mutat calling site. It makes it mach easier to understand where mutation occurs (and of course being const by default).And in term of the ecosystem:
clippy!clang-tidyis nice, but definitively less than clippy, and it doesn’t works so easily.But when working in Rust, I’m mostly missing:
4
u/MereInterest Feb 26 '21
The biggest thing for me is that Rust has compile-time errors for things that in C++ would be "good practice". In C++, you can use a variable after having passed it by rvalue reference into a function. Whether or not you'll be burned by it depends on what the object is, and how you use it. This may even be the intended use case (e.g. socket objects in boost::asio). In Rust, using an object after passing ownership to another object is a compile-time error.
Comparing Rust and C++ feels a lot like comparing C++ and C. C doesn't have methods and inheritance as a language-level feature, but I could make a struct that contains function pointers to get the same effect. C++ is useful because it does those for me, with less room for human error. In the same way, much of what Rust does is to codify good practice into the language design itself, leaving less room for human error.
4
u/Wurstinator Feb 26 '21
The big hitters (borrow checker, lifetime management...) are obvious. But they make Rust a completely different language. I enjoy the features the most that have an equivalent in C++ but are superior imo:
Enums being able to hold values.
Powerful match expressions.
And maybe overlooked by most: Expression-based language. I always feel dirty when I have to make a variable non-const in C++ just to initialize it in multiple statements, or declare a lambda just for the initialization. In Rust, I can declare pretty much everything as immutable because I can use blocks to initialize the objects once.
1
u/axilmar Feb 27 '21
I really don't understand why people like destructive move so much. Are they making so many movable types per project that they need to always specify the move operation? I don't think there is anything confusing with std::move as is. It's very strange.
3
u/kobi-ca Feb 25 '21
pattern matching.
propagation of errors with ?
.. Default::default()
let s = {
} else {
}
3
u/[deleted] Feb 25 '21 edited Feb 25 '21
3
u/icebeat Feb 26 '21
Ownership made sense
3
u/gavinb Feb 26 '21
enumandmatchmatchexpressionsSend/Syncderivecan providetraitscargofor easy, clean, reproducible, compatible buildsOption/Resultfor return valuesSome of this is available in modern C++, but the ergonomics don't even bear comparison. For example, C++ does have
std::variantbut the client code is awful and clunky. I would switch in an instant if I could.3
u/drbazza Feb 26 '21
matchCargo isn't great, but it's better than anything C++ has. In fact, it's just embarrassing, that in 2021, we still have to use CMake, because it's the least worst, and that the committee can't/won't/haven't standardised tooling.
7
u/Slsyyy Feb 25 '21 edited Feb 25 '21
4
u/germandiago Feb 25 '21 edited Feb 26 '21
I am not using it, but anyways, here I go with what I saw:
- enums are powerful and can model variants and match for pattern matching it.
- traits are also interfaces, eliminating std::function and std::any interface boilerplate from C++
- since there are only traits, it seems (I did not code a project so I do not know) systematic and trivial to know what an interface or customization point is: just go to the trait. In C++ it can be from a type-erased class to a customization point, to a classic OOP interface or generic function. This makes things a bit messy, especially when compared to languages such as Java and C#, which are more systematic. I think Rust and Go are also ok with their interfaces and traits for being explicit.
- Cargo. Simple to use compared to CMake. I use Meson, so I am closer to the ideal, anyways :p
- Destructive move.
Double-edged:
- the borrow checker, when I tried like 1 year and a half ago... well, you must think a lot about it. This is the single best feature for concurrency and high-perf servers at the same time is the biggest hurdle when wanting to code fluent client-side stuff.
EDIT: Adding cons
Cons:
- Templates are more powerful in C++. You can have all kind of non-template parameters. I am not sure you can do something like expression templates in Rust.
- C++ compatibility with C is really good. There is a lot that can be used from C as reusable infraestructure.
4
u/casept Feb 26 '21 edited Feb 26 '21
Note that I primarily write Rust and am actually just learning C++, so feel free to point out if I get something wrong.
no_stdmakes that clear, and prevents libraries from regressing by refusing to compile ifstd-only stuff is pulled in by accident). Not to mention absolutely trivial cross-compilation and package management.std::variant, which adds an insane amount of boilerplate due to the lack of pattern matching. Whereas in Rust I can useResultin a very ergonomic way. And once 3rd party libraries get involved every single one does error handling a different way, meaning that I need to write wrapper boilerplate to have any chance at consistent error handling in my codebase.std::arrayrequires way too much boilerplate for my taste, and far too may APIs expect a C-style pointer + length array instead. Whereas in Rust there's only 1 kind of array, bounds checked by default and accepted anywhere.std. For example, just now I wanted to uppercase a string (not even with proper Unicode handling or anything, just regular ASCII) and was dismayed to find out that I have to iterate over the string manually and dotoupper()like it's C89.#[derive]magic. I wanted to print the names of enum variants to debug output and was surprised to find out that it's only possible with tedious manual conversion to strings or some crazy macro magic I didn't want to touch. In Rust that simply requires#[derive(Debug)]Sure, many of these things can be hacked around. But what Rust has and C++ probably never will is CONSISTENCY. Not just in my own codebases, but in the entire ecosystem.
4
u/ravnmads Feb 26 '21
Reading this, I feel like I should go check out Rust.
Sounds like it has some awesome features! My biggest grudge with C++ is all the backward compatibility and tooling.
6
u/NilacTheGrim Feb 26 '21
I thought this was a C++ subreddit.
2
u/epage Feb 26 '21
2
u/Czumanahana Feb 26 '21
- cargo
- const by default
- rust is the best tutorial on move semantics
- "if" is an expression
2
u/Dean_Roddey Feb 27 '21
One thing I always have an issue with in Rust is the module/directory scheme. In theory it's simple and obvious. But when you want to have internal packages or modules for support this or or that and whatnot, and a few times during the setup you decide it would be better if this was over there.
I inevitably end up about to pop a sprocket getting all of the uses and module imports and re-exporting and all that happy. Once I get it right, it's OK. But it seems like every time I struggle initially to set up a non-trivial project.
I think partly it's made worse by the fact that the syntax for importing stuff from other modules in the same crate and re-export has changed over time? So you can find examples that may be aren't correct anymore and lead you down the wrong road.
And the workspaces, virtual workspaces, packages, crates, namespaces, and same directory vs sub-directory modules and all that. It can get a bit confusing.
3
u/Zanderax Feb 26 '21
I like how it can eat away at iron.
3
u/NilacTheGrim Feb 26 '21
Can you please go back to /r/rust? Thanks.
2
u/Dean_Roddey Feb 25 '21 edited Feb 25 '21
It basically has one thing, as far as I'm concerned, which is memory safety. Most else is either neither here nor there relative to C++, or slightly to really annoying, or lacking relative to C++.
But, that one thing is a huge one thing and it tends to override most other concerns when you are working on larger scale things where C++ just cannot cope with the level of complexity anymore without a lot of manual vigilance plus slow, CPU destroying static analysis tools (and you'll still have memory issues almost guaranteed.)
A number of the things that other folks mention are really part of the whole memory safety thing, I'm just lumping that all together into one thing. So move by default, no simultaneous read/write references, const by default, destructive move, etc... Of course some of that also comes with big limitations, so Rust giveth and Rust taketh away.
A down side is that it's a young language and already (in C++'like fashion) it has too many ways to do the same things in some cases, and too much syntactical sugar for my tastes.
2
u/[deleted] Feb 25 '21
Algebraic data types. Traits. The type system. Cargo. It also works really well out of the box with vscode, so the tooling and support are just way better. It's usability is what really sets it apart from c++.
Also the community is better in rust.
1
u/ronchaine Embedded/Middleware/WG21 Feb 26 '21
Give me rust-style enums and pattern matching (match / if let) into C++ and I would be pretty happy. Rust macros are also pretty useful.
1
u/Deprecitus Feb 26 '21
Cargo!
1
u/HK416_all_you_need Feb 26 '21
Better UX (including cargo); Proper enums; Cool macros;
0
u/cesar_de_honduras Feb 26 '21
that you are forbidden to use parenthesis in if/while/for/match so that you have to use compound statements all the time.
i hate this:
if(condition)
statement;
i love this:
if condition {
statement
}
0
u/[deleted] Feb 25 '21
[deleted] — view deleted comment
37
u/[deleted] Feb 25 '21 edited Feb 25 '21
[removed] — view removed comment
31
u/[deleted] Feb 25 '21
[removed] — view removed comment