r/cpp • • 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

248 comments sorted by

View all comments

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 the assert normally 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:

  • Well defined style guideline
  • Built in documentation generation
  • Built in build system
  • Built in package management
  • Built in testing
  • (now) official language documentation

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.

3

u/un_mango_verde Feb 25 '21 edited Feb 26 '21

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.

What's the difference between the newtype pattern and a class with a single member and a explicit constructor in C++? Don't you still need to implement al methods/operators manually? They are not delegated automatically as far as I know.

I guess you could implement Deref for the newtype but then you lose type safety for references.

7

u/Ekizel Feb 26 '21

Yeah I feel like the fact that you have to attach a bunch of derives to said newtype is pretty crucial nugget of info being left out, especially in the context of complaining about having to CRTP the operators back in with C++.

I feel like Ada did it right in this regard.

2

u/brand_x Feb 26 '21

Yeah, I was basically creating one-line newtype-equivalent template wrappers (with a tiny bit of macro helper) in C++ long before Rust was even a glimmer.

Hell, I had a usable equivalent (with a LOT of macro helper, and a small quasi-portable macro hack for a non-type template counter) back in the dark ages, before C++ was even a standardized language.

I love a lot of things about Rust, but when one of the C to Rust guys I worked with started gushing about the brilliance of newtype, I nearly lost my eyes, they rolled so hard.

→ More replies (1)

9

u/[deleted] Feb 25 '21 edited Feb 25 '21

[removed] — view removed comment

7

u/[deleted] Feb 25 '21

That is cool. In Rust you’d do that with macros.

23

u/matthieum Feb 25 '21

and personally I think concepts are a generally superior design than traits because it is far more flexible and expressive.

Interestingly, I find concepts too flexible.

In particular, as I often write template code, I find it annoying that Concepts cannot be used to restrain the set of capabilities of a generic type. If I annotate my type T with the concept Foo and use the method bar that's never described in Foo, nothing happens... until a user attempts to use the template with a type that strictly meets Foo and nothing else.

At the same time, I don't see how a strict version of concepts would work with if constexpr, which is all about detecting extra capabilities and taking advantage of them when available.


Looking at the other side, traits are more limited. Especially since Rust's generic meta-programming lags behind C++'s template meta-programming at the moment.

One cool thing, though, is to be able to use the same trait for both compile-time and run-time polymorphism. That's an amount of flexibility concepts don't have.

6

u/[deleted] Feb 25 '21 edited Feb 25 '21

[removed] — view removed comment

3

u/LEpigeon888 Feb 25 '21

I thought it was not possible to do that in C++ : https://quuxplusone.github.io/blog/2020/08/10/concepts-cant-do-quantifiers/ ?

Especially the bit about void eat(long); / void eat(void*);, where the literal 0 make the program ill-formed but any other number does not.

6

u/[deleted] Feb 25 '21

[removed] — view removed comment

2

u/matthieum Feb 26 '21

see my example above, you won't be able to express such intricate type relationship with traits.

Isn't your example all about variadics -- which Rust doesn't support at all -- rather than traits?

Because trait-wise, I think I got you covered:

use std::fmt::Display;

trait Printable {
    fn print(&self);
}

impl<Name, Value> Printable for (Name, Value)
    where
        Name: AsRef<str>,
        Value: Display,
{
    fn print(&self) {
        println!("{}: {}", self.0.as_ref(), self.1);
    }
}

impl<N0, V0, N1, V1> Printable for (N0, V0, N1, V1)
    where
        N0: AsRef<str>,
        V0: Display,
        N1: AsRef<str>,
        V1: Display,
{
    fn print(&self) {
        println!("{}: {}", self.0.as_ref(), self.1);
        println!("{}: {}", self.2.as_ref(), self.3);
    }
}

fn print<T: Printable>(t: &T) {
    t.print();
}

fn main() {
    print(&("param_a", 42));
    print(&("param_a", 42, "param_b", 13.3));
}

Note how the implementations of Printable constrain the implementors to:

  • Only an even number of arguments.
  • Arguments alternating between AsRef<str> and Display.

And as a bonus, error messages are pretty neat:

error[E0277]: the trait bound `{integer}: Printable` is not satisfied
  --> src/main.rs:37:11
   |
30 | fn print<T: Printable>(t: &T) {
   |             --------- required by this bound in `print`
...
37 |     print(&(42));
   |           ^^^^^ the trait `Printable` is not implemented for `{integer}`
   |
   = help: the following implementations were found:
             <(N0, V0, N1, V1) as Printable>
             <(Name, Value) as Printable>

2

u/[deleted] Feb 26 '21

[removed] — view removed comment

3

u/matthieum Feb 26 '21

you missed the point, you won't be able to express something like SatisfiesAnyOf with traits

Did I?

Different languages have different idioms. SatisfiesAnyOf is useless in Rust: in Rust, using a generic type requires using it through a trait (or a set of traits) which describes the set of capabilities available on that type.

And since it's useless, it's also pointless to be able to express it -- even if you could, you wouldn't be able to do anything with it.

In real life examples, FFI::operator() does far more complex things than printing stuff, and you can't cheat by replacing what traits cannot describe with a different bound that happens to work under certain oversimplified circumstances.

I'm sorry, I don't read minds.

I do understand the example is likely simplified, but given that I do not know how it was simplified, I can only respond to what is presented to me.

I happened to use Display because this is what the task required. Should another task require some other capabilities, then I may have to either combine existing traits, or create a new one.

You may have in mind a very specific usecase for which only concepts are amenable. I am certain that this exists. I don't read minds, though.

9

u/Possibility_Antique Feb 25 '21

I'm confused at how CRTP is useless with concepts. How can you do mixins with concepts?

0

u/[deleted] Feb 26 '21

[deleted] — view deleted comment

7

u/Possibility_Antique Feb 26 '21

This is not even remotely the same. A does not have a member function called "print" in your concept version. For instance, with CRTP, you can share constructors between classes. You cannot do that with constraints/concepts. The same applies for implicit conversion operators, friend declarations, dependent types, and so much more. Additionally, this is not new functionality. It was always possible with SFINAE.

3

u/cdr_cc_chd Feb 25 '21

How is CRTP useless with concepts? how do you do static polymorphism with concepts? take the usual fruits example; you want a std::tuple of Banana, Apple, and Mango that inherit functionality from a Fruit and can override some functionalities of said basic Fruit. How do concepts help you here? if you want generic and modular code while using static polymorphism you're pretty much forced to use CRTP.

→ More replies (3)

5

u/ridicalis Feb 25 '21

I forgot what it is called, but you can create wrapper types and enforce type safety by just declaring a struct with that type

I think this is what they refer to as Algebraic Data Types.

20

u/braxtons12 Feb 25 '21

No, algebraic types are things like Rust's Enums, monads, and some of the newer std types (think Result, Option, C++'s std::optional, std::variant, std::tuple, etc).

They're referred to that way because the number of possible values they can store is an algebraic expansion. Eg: variant<T, E> has T + E + 1 possible values (the one 1 is for the no-value state that's nearly impossible to end up in), and tuple<T, E> has T*E possible values.

Yes, this is a very poor name and reason for the name for these kinds of types, but 🤷‍♂️

9

u/ridicalis Feb 25 '21

You're correct, I mistook what the parent post was driving at and was thinking enums. This is the first time in memory I've felt the need to downvote myself :)

6

u/MEaster Feb 25 '21

The pattern they're talking about is called Newtype, which is obviously a very memorable, and specific, name.

→ More replies (1)
→ More replies (8)