128 points · by rnestler · 11y ago · 107 comments
The add_one example, as simple as it is, is a horrible example.
Why not embrace value semantics and write it like:
int add_one(int x) { return x + 1; }
There is simply no need for pointers or references. Write simple code first. To the heap allocation example: auto x = std::make_unique<int>(5);
Even if this is a silly example, just say no to unnecessary heap allocation. Why not: int x{5};
Now to the lifted example: void add_one(std::unique_ptr<int> num) {
* num += 1;
}
This mixes operations with lifetime management. The add_one function does not need to care about ownership. And it does not need to take ownership of its argument. Instead on the call site do: int add_one(int); // from above
auto p = make_unique(5);
auto six = add_one(*p); // <-
There are valid points in the blog post and I know that most snippets are meant as examples. But as someone writing C++14 you can't win me with those kinds of posts, even though I'm having a fun time playing with Rust in my spare time.For more about modern practices see: http://klmr.me/slides/modern-cpp/
Also see Howard Hinnant's unique_ptr tutorial: http://howardhinnant.github.io/unique_ptr03.html
All of your examples look almost identical in Rust and C++. That's not a positive, nor is it a demonstration of similarity - it's a useless set of examples for a post _demonstrating the differences_ between the two. :P
It's worth looking at each of the examples in the article and thinking about them in the context of the more complex practical problem that do _require_ mutable/heap state.
Again, think of the examples as 'C-Reduce'd[1] ones - just enough for an experienced programmer to 'get' the differences and infer its relevance to real world cases.
To give at least one motivating example: for your first case (functional add one) - that's entirely passable for the (tiny) int, but quite useless for the larger case of BigInteger. That's where Rust's default move semantics would really shine, but using BigInteger as an example would introduce lots of irrelevant semantics, making the example bigger but scarcely more informative.
Where are the Rust explicit lifetimes in this example? If the C++ code has been made intentionally obtuse with unneeded measures here, why aren't Rust lifetimes (which I think are a terrible wart on the Rust language but are absolutely necessary for non-trivial ownership scenarios in Rust) captured in this example?
Rust has a feature called 'lifetime elision.' Three rules, that removed the need for virtually all (iirc, something lie 95%) of explicit annotations in the compiler.
The first rule is the one that applies here:
fn foo<'a>(x: &'a bar) {
can be written fn foo(x: &bar) {
That is, if there is only one lifetime annotation, it may be elided. The annotation wouldn't do anything special in this case, and so is just boilerplate.See my point with making the add_one function not taking a unique_ptr. This is valid criticism and valid in more complex practical examples, too.
BigInteger& add_one(BigInteger& num)
is an awful function (really no checks of any kind, such as multiple holders). You suggest that it's valid for more complex practical examples, but that's a simple example where you'd probably want: void add_one(std::unique_ptr<BigInteger> num)
BigInteger is a common example often written in fluent/mutable style or to take ownership of the argument in just this way.But in general, I think some of the advantages of Rust boil down to "compiler enforcement of stuff that good practitioners of modern C++ already do". And that's a good thing.
Thanks for your links, which are great!
Seeing last year's CPPCon videos was illuminating to me.
A big problem is that many are still writing pre-C++98 style or chained to style guides that prevent many of the C++11/C++14 improvements.
Specially problematic when IT is the one calling the shots to what is available in the development environments.
You can no-true-Scotsman code that compiles, runs, and blows up in your face with any modern C++ compiler all you want, it doesn't change the fact that Rust eliminates entire classes of errors that are trivial to hit in C++.
Until then, it is going to be "Modern" C++ for the lower layers/common code, with the platform vendor languages for the upper layers, regardless how Rust improves over C++.
I am a big fan of the type safety of Pascal and ML language families, but eco-systems have more weight than just the language.
If anything, this sort of post is more convincing to a junior developer who wants their compilers to do more to warn them when they've done something stupid. They want to write idiomatic C++, but they're lazy and inexperienced, so if there's a language where the compiler provides feedback when they deviate from what's idiomatic, they're going to opt for the feedback.
I'd be very interested in what's drawn you into trying Rust and what you think are the most redeemable qualities.
One thing I like about Rust is how you e.g. can specify a Sortable trait and then with T: Sortable require it for types. This will eventually come to C++ with Concepts (lite), for now there are ways to work around this, e.g. with:
#define requires(...) typename enable_if<(__VA_ARGS__), int>::type = 0
template <typename T, requires(is_integral<T>())>
void fn(T);
Without a feature like this you may see cryptic errors from inside template instantiations coming from your stdlib, when you try to sort something that is not sortable.Something I realized at some point is that these "language A vs language B" comparisons aren't really there to convince adherents of language B to switch to language A. You'll see lots of comparisons on the web of Haskell/Scheme/Lisp/C#/F#/Ocaml etc put up against really poorly written C/C++ code, with "language A" inevitably coming out of the comparison pretty well.
Thinking back to my days at school, a lot of physicists were telling each other that if they wanted their simulations to run in a reasonable amount of time, they had to code them in C. These comparisons are really aimed at them - the message here is, "yes, a really great C programmer could write machine-optimal FFTs or whatever in C, but the code that you, a beginner, will end up writing could actually end up being not much faster and in some cases perhaps even a lot slower than the equivalent code in Haskell/etc".
Compile time checking attracts more than just the lazy and inexperienced.
(Maybe you didn't mean to imply otherwise, but it sure as hell reads that way.)
I personally find C++ is fine and dandy if you're working with a disciplined team. On the other hand, it's bad qualities are immensely magnified when the overall team lacks in talent and/or experience.
There is a real difference between a safe language, and a safe subset of an unsafe language that gets verified by some guy (no disrespect). The former is (everything else being equal) just way better for everyone involved, especially for the guy.
hear, hear... Few of my recent features were passing through 7 layers owned by 4 teams (C++) with one team also having Java subteam (who seem to have never heard about Java coding style, etc...) Each team has a person who like you is enforcing his the _only_ right way ... which happen to be different from each other. Well, i just code to whatever style that module is written in :) After 25 years in the industry i've seen a lot of "right ways"...
>The add_one example, as simple as it is, is a horrible example.
>Why not embrace value semantics and write it like:
int add_one(int x) { return x + 1; }
>There is simply no need for pointers or references. Write simple code first.yea, man. That particular style is there too. Slow as hell. Works for the teams of really average programmers who can't grasp and keep together in mind more than one simple aspect of a small piece of functionality at a time.
rust_dangling.rs:6:5: 6:6 error: cannot borrow `v` as mutable because it is also borrowed as immutable
rust_dangling.rs:6 v.push(6);
^
rust_dangling.rs:4:14: 4:15 note: previous borrow of `v` occurs here; the immutable borrow prevents subsequent moves or mutable borrows of `v` until the borrow ends
rust_dangling.rs:4 let x = &v[0];
^
rust_dangling.rs:8:2: 8:2 note: previous borrow ends hereFor example, sometimes you may declare something with some odd syntax and Rust effectively say "I was expecting type `A`, but this is type `B`." Frequently, I want to have a little more insight into what's going on, but the inability to maybe write some code that will print out information about something causing a compile error is problematic.
That's the thing about Rust: because the burden of debugging is so shifted to the compilation step, Rust absolutely HAS to have good error messages because that's all you have to work with.
However, I feel this shift in workflow can be overcome with different tooling, and I suspect this is mostly a symptom of being new to the language.
The quality of the error messages is a property of the compiler, not of the language. But of course, a well-designed language also provides the abstractions that ultimately can lead to good error messages.
Which I find fitting, since in Rust, the Box is (at least to me) more about indirection. The single-owner semantics just come in because Box follows the same rules as anything else, while for unique_ptr they are part of the pointer concept.
As far as I know, the compiler should not copy in that instance. Rather, it should move.
> There is not one unit of memory that is "taken over," or if there was, then Rust would have a serious problem.
Could you elaborate on that? Rust does have an ownership model, and ownership can be transferred as in the example. What sort of problems would you expect that to cause? If you're worried that it will invalidate existing pointers, the compiler checks that for you. Unless you deliberately circumvent the check, the compiler guarantees that your pointers are valid.
If the value isn't passed by (perhaps elidably) copying, that would mean it's getting allocated on the heap and deallocated.
But it can't have backpointers. That would violate single-ownership. Weak pointers for backpointers are available, but that's an unstable feature and introduces reference counting overhead. Rust needs some construct which includes a single-ownership forward pointer and a dependent back pointer, updated together so that they're always in sync.
Rust has the concept of a possibly-null pointer; you just have to write it explicitly by wrapping something in the Option type. In particular, Rust has a guaranteed optimization that says if you have a type with a single zero-argument constructor and a one-argument constructor, and the one-argument constructor takes a type that can't be null, then the type with those two constructors will just use null to represent the zero-argument constructor. So Option on a pointer/reference type just represents a nullable pointer.
But yeah, that probably ought to end up in either the standard library or a very common third-party library, at some point.
I really need to think this through and make a proposal for Rust 2.
Anyway, Rust is simply a language with a lot less cruft, combined with a better tool chain (compare rust compiler errors to g++ compiler errors). That's not a surprise, considered C++'s age (30+ years). OTOH, without C++, Rust would have been impossible. OTOH2, Rust wanted to be somewhere between C++ and OCaml. I think they succeeded.
Much of the "cruft" of C++ stems from the template system. Rust has very sensibly decided not to go down that path. But aren't you happy that one language has sacrificed itself so that we can express ideas like this...
template<typename T, size_t A, size_t B, size_t C>
Mat<T, A, C> matmul(const Mat<T, A, B>& left, const Mat<T, B, C>& right) {
...
The actually useless features like exported templates and trigraphs, are removed.But adding new keywords instead of reusing/overloading old ones for newer features would have been nice. Writing new code in C++11 isn't the problem, reading old ugly C++ code and trying to understand it is. I think the clean break is Rust and it already looks promising. Sure some of its syntax is influenced by non-C languages and looks a bit weird, but I can live with that.
There's been a number of different benchmarks, in a bunch of places. We generally end up in the same realm as C++, sometimes faster, sometimes slower.
Also, many benchmark authors seem to accidentally compile Rust code without optimizations. We're considering switching Cargo's defaults because of this.
Another good example is that the borrow checker is currently based on lexical scope. See all the examples in https://github.com/rust-lang/rust/issues/6393 .
In general, any kind of analysis like the borrow checker will reject some valid programs, as it pays to be extra conservative. You then slowly expand the set of accepted programs, until hopefully, it matches the true set of valid programs, without accepting invalid ones.
What kinds of pet patterns have you seen?
This kind of thing happens any time you transition languages: when I started hacking on Rust, I was trying to figure out how to do the metaprogramming shenanigans that Ruby lets me do. Ironically, Rust's metaprogramming features are my biggest weakness as a Rust programmer, I don't really write my own macros.
I'm wondering, is this possible in principle?
Context: I'm thinking in terms of sound-and-decidable type-checking conservativeness [0], but perhaps that's a bad way of thinking about this? Perhaps borrow-checking is a special-enough case of type-checking that somehow isn't afflicted by this (how?) or gives up the soundness (does it?)?
[0] "A sound type system with decidable type-checking (and possibly decidable type inference) must be conservative." -- http://gallium.inria.fr/~remy/mpri/cours1.pdf
See also: https://books.google.com/books?id=7Uh8XGfJbEIC&pg=PA134
In real world, abstraction is a lossy process. From "white horse" to "horse", we lose the information about color. And this lossy nature of abstraction is important, as it become simpler. This should be differentiated from saying "horse" but actually meant "white horse", because in that situation, it is not abstraction but omission. The complexity is still there (or even more).
In programming, add types or mutability increase the complexity. In that regard, Rust is simply more complex. But that is not what I commenting on. I am commenting on the trend in programing to hide that complexity by omission (such as type inference) or make it implicit such as using key word 'let' and 'var'. They only make the user less aware of the complexity at surface.
Now I am not saying language designers are not doing the best they can do (earn both honest and popular credits); but I have been thinking what might be the ideal way to handle complexity, and I only can see how we are doing it with our natural language. In our day to day business, when we say horse, we do not care about its color, and any one who interprets the sentence (with horse) is fine to imagine either a white horse or black horse or any but need understand the color is not important. So in analogy, in high level abstraction, we should be allowed to say a number with no type but be understood by the compiler that any number will do, which may even include a byte. Then the language should allow us to declare specific type as well -- just like in real life we should be able to directly say "white horse" if the color is meant to be important. Which means we should be able to specify an integer with 64 bytes long (I don't think we ever really need arbitrary precision) if we deem critical. We should note that I am not referring a dynamic type, nor an optional type system. The type is always specific at very low level (cpu level). The compiler decides for us when we don't say and we don't say when it is not important any compiler decision is ok.
Of course this is not realistic and the reason is simple. The way we do daily business leads to imprecise implementation. I say horse, and it can be implemented either as a white horse or black horse or anything in between (hopefully a common one at least). It is tolerated in our daily life because the implementation is often cheap and can be directly verified at every level. E.g. I say get me a horse, I verify your facial to see if you heard, and verify you action to see if you are about to act, and I get in between gossips to get warnings of any surprises, ..., all the way until I actually have the horse. And along any of these steps, if I find I actually meant a white horse and you are not getting a white horse, I interrupt your implementation and make corrections. In programming, writing code is expensive (programmers are paid well, takes long time), and the typical only feedback is when the code completes and the user uses the software (at which point the user is getting the feedback, not programmer), and when things go wrong, user have no idea how to make correction, and this is even true for programmers, who have no idea what is inside their libraries and the nuances of the programming languages they are using.
TL;DR We are stuck.
To solve this scenario, I think the first step is to make every one be able to program, then the implementation can become cheap, and the feedbacks can become short and quick, and the compiler can become less rigorous, and then we may be able to program like we speak -- program the way we thinks.
We then use do a natural language parsing (NLP), and transform the output to Prolog code. We execute the Prolog code and use a search engine to find the solution. Each result is used an input for another (second) search step. We score each result and do something with it. That's more or less how IBM Watson works.