175 points · by kkimdev · 7y ago · 86 comments
E.g. since immutable references are the default, you immediately know whether or not a call will modify its argument. E.g. the existence of traits and compiler warnings for style mean that method naming conventions are incentivized, because implementing a trait usually gives you a lot for free. Even performance characteristics are very predictable, a statement which I can only otherwise make about C and assembly (and those are not predictable at all in other ways).
Yes, the memory safety does play into this. It's much more than that, though: memory safety is just one factor in a kind of pervasive predictability that the language encourages through its very design.
At my $DAYJOB I write a lot of Java, and modern full-featured IDE's for Java like IntelliJ are absolutely awersome for refactoring. Most common refactorings are fully automated, and many more complex things are very easy to do by combinding some of the base refactorings.
I really like writing Rust in side projects, but after getting used to the phenomenal support refactoring support in Java, having to follow the compilers diagnostics feels very primitive.
I'd hope that as Rust grows in popularity the tooling will come from that so I'd keep an eye on the intelliJ rust plugin or rider support for rust because as you say, it's really difficult to go from a day job where for example promoting a local variable to a parameter (with replacement at the call sites) just works to one where you actually have to think about manual refactoring.
That has always been my refactoring algorithm with C++, C# of TypeScript now. I know a lot of smart people using dynamic languages but I always prefer to lean on the compiler to tell me what needs to be changed.
As someone who has been working mainly in Rust for about a year and is now starting to pick up Python, this is huge! I pretty much never write Python that isn't explicitly typed thanks to how Rust changed me as a programmer.
You do not, since the type of which an object is referenced could use interior mutability (e.g. RefCell). So, you only know if this is the case after inspecting the type.
Of course, the default in Rust is to use exterior mutability and in general, interior mutability is/should be avoided.
(I agree with the general thrust of your comment though.)
Though, for the people who haven't explored Rust yet, I still think that focusing on the memory safety, the most powerful feature, is a good approach. Personally I tried explaining other smaller benefits first, e.g., immutable by default, move by default, no header files, but didn't work well as I thought. Exploring another language is a significant investment, and people need a significant reason (at least those that appear to be at first glance).
The language is just overwhelmingly better to code in than C, or Java, or C#, or Go. If the compiler were to be made fast -- and there is nothing like a fast compiler coded in your language to advertise its speed (and the reverse!) -- or anyway JITted, with a REPL, it could replace a great deal of scripting.
The comparison to C++ is much less compelling. Rust fans like to lump C and C++ together, but in modern C++ there are few temptations to memory unsafety. (They might be misled by crufty Mozilla code.) Meanwhile, the greater expressivity of C++ enables more powerful libraries, and each use of a good library eliminates many more than just memory bugs.
No these limitations routinely get in the way for ordinary applications. The borrow checker is a source of frustration when ramping. Back-references get smuggled in as array indexes. Prohibiting global variables is tough. Any sort of app that can't be structured as a tree is going to have pain.
This safety is really valuable, but let's not pretend it comes for free.
For example consider an API like JS's getElementById(). In Rust, if a caller frame has a reference to the same element, this would just panic. It's impossible to statically enforce that no caller can have a reference to this element, and it's unreasonable to require it at runtime. So you either give up safety guarantees (viable, e.g. gtk-rs, but it leaves Rust anemic) or you give up the entire programming model (maybe viable, still a research project).
The most straightforward way to get it working would be to return a `&Element` (or `Rc<Element>` if you like), and make all of `Element`'s fields `Cell`s. No panics, no runtime checks, and you can do everything JS can do. The cost is "infecting" the type definitions with `Cell<T>` and the usage with `.get`/`.set`, and the loss of what is normally rich pointer aliasing information for the optimizer (but which other languages don't have to begin with).
The reason Rust `&mut` feels so restrictive is that it allows you to change the "shape" of the object, thus invalidating (if they existed) any other references into it- replace an enum value with a new variant, reallocate a `Vec`, overwrite a `Box`, etc. But in other memory-safe languages you can't do any of those things. Instead any "shape changing" is done by allocating a new GC'd value and overwriting a pointer- enums are boxed (or don't allow interior pointers), arrays only contain primitives or pointers, etc.
So I like to think of `&Cell<T>` as a kind of third reference mode, that matches what people expect from other languages. It's not fun to use today, but there are a couple of language additions that could make it much, much nicer:
* First, field projection- given a type `struct S { x: T }` and a value `r: &Cell<S>`, let `r.x: Cell<T>`. This is safe as you can't invalidate `&r.x` by overwriting `r`- but by extension you can't project a reference through a `Cell` into an enum or `Vec` (just like other languages as described above).
* Second, some syntactic sugar for reading and writing. Replace `cell.get()` and `cell.set(x)` with `cell` and `cell = x`. Given that `Cell` has zero overhead (other than the loss of optimizations described above) this shouldn't be an issue.
Shared mutable state and ownership exists in C, but I just don't get any compiler support for it. I can't even document it in code, so I (and users of my libraries) rely on RTFM.
In C I'd just "wing it", and tweak the code until it stops crashing. Maybe add a flag with "obj.free_data_ptr = true" and keep adding mutexes or copies of data where I suspect it's necessary.
In Rust I get predefined templates for this — owns & borrows, cells/atomics, refcouted and mutex containers, etc. The compiler says "nope, this is wrong!" and I get to conciously decide how to solve it — do I share or copy the data? Is the sharing dynamic, or just in a wrong scope? And my decisions are documented in code, and enforced by the compiler.
std::vector<int> x = {1, 2, 3};
process(std::move(x));
x.push_back(4);
// Runtime invalid memory accessI can't think of any case that relying on unspecified state is desirable even if it's valid, though I guess it's better if I change that to x.pop_back(); to be clear.
Please let me know if my understanding is incorrect and thanks for the information!
push_back is absolutely defined. pop_back might be undefined, because pop_back is UB on an empty vector. If you like, call clear, and be assured of an empty, reusable vector. It's not idiomatic, but it's safe.
Howard Hinnant had a Stack Overflow reply a while back going through the possible corner cases of this precise question: https://stackoverflow.com/a/17735913
let x = vec![1, 2, 3];
process(std::mem::replace(&mut x, Vec::new()));
x.push(4);
https://doc.rust-lang.org/std/mem/fn.replace.htmlAlthough, are any C++ compilers able to at least issue a warning in this case? It wouldn’t surprise me if they could.
Not necessarily like the example given, but
Object a {std::move(x)};
x.push_back(4);
could/should segfault.Sometimes the compiler calls that destructor after it has finished the move, if the thing is no longer in scope. That should not be confused with a thing happening in the constructor.
int x;
int y = square(x);
// Passing a garbage value at runtime.
My C++ compiler doesn’t build that:error C4700: uninitialized local variable 'x' used
And even then it's still unable to detect anything but the simplest case. E.g. this compiles with no warnings:
void foo(int& x) {}
int x;
foo(x);
int y = square(x);I'm not. The compiler is VC++ with default project settings. "Treat warnings as errors" setting is set to "No (/WX-)"
By default, VC++ compiler turns on this for new C++ projects: https://docs.microsoft.com/en-us/cpp/build/reference/sdl-ena... That's why it fails to build.
https://docs.microsoft.com/en-us/cpp/error-messages/compiler...
So by definition, if it's reported as an error, you're compiling with warnings-as-errors enabled, at least with respect to that one warning.
The default project settings you refer to are Visual Studio defaults (for new projects created from a template), not VC++ defaults. If you invoke cl.exe directly from command line on your code, you'll see C4700 being reported as a warning, but it still produces the binary.
/WX is a switch to treat all warnings as errors, but it's not the only switch that controls warnings-as-errors behavior - you have all the other /W... switches, from level-based approach to setting it for specific warnings. And /sdl is (in addition to all the other things it does) an alias for a bunch of those switches. Indeed, on the very page you linked to, it literally says: "/sdl enables these warnings as errors ... C4700". And you can even override that by doing something like /sdl /wd4700.
The financial system is the safest, most stable, most rigorous, largest and most tried-and-tested system in human history. From ancient times to today, male, female, old, young, wise, stupid, positive, evil, good, evil, With the participation of the whole people in the game, Rust only learned a little bit of fur and took the wrong knowledge, but he also achieved great success.
Therefore, I suggest that computer science should classify financial knowledge as a compulsory course, which has great reference significance for building a safe, efficient and stable system.
from: https://github.com/linpengcheng/PurefunctionPipelineDataflow...