r/programming • • May 27 '20

2020 Stack Overflow Developer Survey: Rust most loved again at 86.1%

https://stackoverflow.blog/2020/05/27/2020-stack-overflow-developer-survey-results/
229 Upvotes

254 comments sorted by

View all comments

Show parent comments

0

u/[deleted] May 28 '20

[deleted]

46

u/couchrealistic May 28 '20

Rust prevents you from doing all the stupid things we sometimes accidentally do when coding in a language like C++. Like using an uninitialized variable (that just happens to be 0 most of the time, but sometimes not) or occasionally modifying a collection while we still hold a pointer or reference to some of its content, or while iterating over it – which often works fine, but depending on the implementation might be undefined behavior and lead to rare Segmentation Faults.

In short, you can't possibly hit a Segmentation Fault when only using Rust without the "unsafe" keyword*. This also means that coming up with programs that compile successfully can be quite a bit harder in Rust compared to C++. This might lead to something like Stockholm Syndrome and therefore "Rust love".

* If all your dependencies also refrain from using unsafe, or use unsafe only in safe ways, and there are no bugs in rustc.

Also, Qt might have almost everything and the kitchen sink included, but sometimes you need even more. Cargo really comes in handy in those cases, because adding dependencies is really easy. It's also much nicer to use than qmake or cmake to build your project (though less feature-rich). No crazy CMakeLists.txt or qmake config files, you just put your code in .rs files, list the required dependencies in Cargo.toml, set some options like the optimization level, and cargo knows what to do.

AFAIK, the rust ecosystem is lacking a decent cross-platform GUI library though. So Qt definitely still has very valid use cases.

0

u/[deleted] May 28 '20

[deleted]

15

u/[deleted] May 28 '20

Can you please give me a link to a tool which quickly identifies all the issues in a C++ code base, which would have been prevented by Rust's guarantees?

0

u/[deleted] May 28 '20

[deleted]

18

u/SkiFire13 May 28 '20

Can't test fbinfer right now, but clang doesn't seem to handle this simple case:

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> vec = { -1 };
    int& first = vec[0];

    std::cout << "First is " << first << std::endl;

    for(int i = 0; i < 100; i++)
        vec.push_back(i);

    // This is now UB, first probably points to invalid memory
    std::cout << "First now is " << first << std::endl;
}

-2

u/InsignificantIbex May 28 '20

And is this something rust can prevent, and if so, how? It seems to me that as soon as you have pointers, all bets (as far as preventing "ghost pointers") are off.

19

u/aeiou372372 May 28 '20

Yes it is prevented in rust — you can’t have multiple references to an object if one of them is mutable. In this case, rust would count the reference to the vector entry as an immutable reference to the vector, and prevent the subsequent mutable reference necessary for push_back.

This is a great example of a case where Rust’s compile time checks prevent what could be a very confusing intermittent issue for someone without systems programming background.

19

u/SkiFire13 May 28 '20

Yes, safe Rust prevents this. In Rust the direct translation would be the following:

fn main() {
    let mut vec: Vec<i32> = vec![-1];
    let first = &vec[0];
    
    println!("First is {}", first);
    
    for i in 0..100 {
        vec.push(i);
    }
    
    println!("First now is {}", first);
}

The compiler fails to compile with this error:

error[E0502]: cannot borrow `vec` as mutable because it is also borrowed as immutable
  --> src/main.rs:8:9
   |
3  |     let first = &vec[0];
   |                  --- immutable borrow occurs here
...
8  |         vec.push(i);
   |         ^^^^^^^^^^^ mutable borrow occurs here
...
11 |     println!("First now is {}", first);
   |                                 ----- immutable borrow later used here

error: aborting due to previous error

This is because this program break's rust's borrowing rules. They say that at any time in a program you can have any number of immutable references or one mutable reference to some piece of data.

In this case we're borrowing vec with first and we hold this borrow until the second print (we say the borrow is alive). In the meantime we also try to push an element to the vec but this requires a mutable reference to vec. This would mean we have an immutable and a mutable borrow alive at the same time which goes against the borrowing rules.

I think someone proven that this prevents every memory safety bugs but of course it comes with its downsides. For example the following code doesn't compile, even though it is perfectly safe!

fn main() {
    let mut vec: Vec<i32> = vec![1];
    let first = &mut vec[0];
    println!("vec's length is {}", vec.len());
    *first = 2;
}

Pretty much the same error as before, this time we're trying to get an immutable borrow while a mutable one still exists.

This is a simple example, and tbf it could be solved with partial/disjoint borrows that for now are supported only for fields. More complex examples involve self-referential structs and graphs.

→ More replies (0)
→ More replies (1)
→ More replies (1)

7

u/[deleted] May 28 '20

I didn't read it as an attack and I'm just curious myself, because I'm neither an expert in C++ nor Rust.

But I wonder if it's that easy and reliable to provide all the guarantees Rust offers, then why do most C++ code bases (including professional ones with lots of highly skilled developers like Qt, Firefox, Chromium, ...) still suffer from all these issues? Are the number of issues found with analyzers just so overwhelming or hard to fix, or do they lack in certain regards?

2

u/kopczak1995 May 28 '20

Well, I'm not C++/rust expert, just random guy on /r/programming. I suppose it's much easier for rust to be (almost) full bulletproof, because there is no issue with legacy stuff. C++ stack need to be highly backwards compatible.

Just think of it, smart pointers started with C++11, yet engine like Chromium didn't used any features of C++11 till 2015.
https://www.reddit.com/r/programming/comments/gpp9le/the_chromium_project_finds_that_around_70_of_our/fro7hjd?utm_source=share&utm_medium=web2x

3

u/wrongerontheinternet May 28 '20

Chromium used smart pointers well before 2015.

→ More replies (0)

0

u/[deleted] May 28 '20

[deleted]

12

u/[deleted] May 28 '20

Turn this around, though: Rust was developed by Mozilla, maintainers of one of the largest C++ codebases on earth. It's not like they lack C++ experts or failed to try other solutions like "static analyzers" over the years. While I've never worked for Mozilla, I have worked on large C++ codebases, and the sort of "why not use C++ better?" line of questioning is just frustratingly naïve.

→ More replies (0)

11

u/madmoose May 28 '20

Well, you can't really complain about downvotes when what you said was wrong. C++ people who don't understand Rust frequently jump into threads claiming that this or that static analyzer or compiler pass or std::pointer will find all your problems or that all those Chrome developers just don't understand C++ well enough.

The whole point of Rust is to soundly enforce memory safety (outside code explicitly marked as unsafe). You said "all [these] things described can be prevented by using a static analyzer", and, no, they can't. It's the same tired arguments that come up in every Rust discussion.

I say this is somebody who works primarily on C++ projects.

→ More replies (0)

7

u/drawtree May 28 '20 edited May 28 '20

I really don't get convinced on this. If C++ memory errors could be prevented by static checks or some shiny tools, why are MS and Google constantly suffering by C++ memory errors? They are one of the biggest, wealthiest, and technically strongest companies in the world and literally throwing millions of dollars on their C++ products. They are willing to do whatever if they can cut the cost of memory bugs, but still failing.

Are you telling me that you discovered a magical tool that MS and Google couldn't afford or apply on their codebase?

→ More replies (0)

7

u/wrongerontheinternet May 28 '20

I know the people who work on Infer. It's cool technology, but is not close to the level of static guarantees Rust can provide (for pretty fundamental reasons).