Never patterns, exhaustive matching, and uninhabited types in Rust
smallcultfollowing.com
smallcultfollowing.com
> if you have to define an error type for some computation, but this particular computation can never fail, you might use an uninhabited type.
I don't see the reason behind returning a Result<String, Err> if there is no error to return. Why not just return a String?
Thanks.
That's fine if you're using it via the Reader interface, but if you're working with StringReader directly it's a pain in the butt to deal with the non-existent exceptions. It sounds like never-patterns would help with that.
See these: https://internals.rust-lang.org/t/recent-change-to-make-exha... https://github.com/rust-lang-nursery/nomicon/issues/29 https://github.com/briansmith/ring/issues/416
However when returning ! the compiler can optimize the entire error handling away.
I think what they're asking is "if you're returning a Result<String, Err>" but you're making the Err an unhinabitated type (so can't ever have an error) why not just return a String in the first place?
By choosing an unhabited return type, you can express that the stream never stops producing values by itself.
Uninhabitable types allow the implementer to tell the compiler "I cannot provide an error here", giving the compiler more information to work with when optimizing. For example, the compiler now knowing that the function call cannot return an error may make it so that the function does only return the string after optimization, and the compiler can also drop the error checking code in the caller because it's unreachable.
[0]: http://fog.io/
Removing checks for "cannot possibly happen" cases isn't usually worth the tiny time savings.
Of course it failed, and it was a royal pain to get to the bits that failed because they were embedded in concrete that was probably holding the building up.
You build for robustness because you might be wrong, the new guy might not understand, or a silicon isotope might decay at just the wrong time and flip a bit. Circuits are analog. They just pretend very very hard to be binary. Weird shit can happen that shouldn’t be possible.
On the other hand, the use of an uninhabited type means that the programmer has to prove to the compiler that the type is uninhabited, in the same way that declaring a function as returning a String requires the programmer to prove that the function actually does return a String. If we have a function that returns a String, the compiler does not generate any code to handle the case where that function returns an integer instead; that just doesn't make sense, we've used the type system to prove that can't happen. Likewise, it wouldn't make any sense for the compiler to generate code to handle the case where a function returning an uninhabited type returns anything at all.
If anything, you probably want something more like Erlang's supervision hierarchy where pattern-match failures (due to a cosmic ray, or anything else) kill the actor-process that was running, and then the actor's parent reinstanciates it and it tries again. Then you just need to draw fine-grained failure boundaries (i.e. what things end up in new actor-processes) to ensure that crashing out a process doesn't waste too much work unnecessarily.
Or the Mars-rover "six CPUs on separate NUMA nodes are each running a copy of the program, and quorum-consensus on the result of each function-call" strategy, but that's a bit expensive.
I don't know about C++, but it may be doing something different from Rust here. In Rust, the ! type (which I pronounce "Never"), isn't just a case of "I, the programmer, don't think any value will exist here"; the compiler forces you to prove (just like every other type is a proof) that a value can't exist. The Never type can't be instantiated (it has no constructor), and functions that "return" Never must prove that they, er, never return; imagine a function whose body is just `loop {}` (or the stdlib function process::exit, which cannot return by dint of killing the callstack when the process dies).
noreturn mainloop(State* s)
{
for(; s->valid ;s->itick++) do_step(s);
die(70,"invalid internal state");
}Uninhabited types are useful for expressing units.
I'm writing an app that makes heavy use of a Haskell library[1] that implements currency units and exchange rates using uninhabited types (type-level strings).
So, one dollar will have the type `Amount "USD"`, whereas one Euro will have the type `Amount "EUR"` (both will have a value of `1`).
An exchange rate from Euros to dollars will have the type `ExchangeRate "EUR" "USD"` (the first type parameter being 'source' and the second 'destination'), and its value will be `1.14` (the current exchange rate from EUR to USD).
A function for converting an amount in one currency into another currency unit will take two arguments: `Amount src` and `ExchangeRate src dst` and return an `Amount dst`.
Also, in general, it can be useful to:
1. Remove an argument from a function
2. Create an uninhabited type that, at the type level, represents the values of this argument
3. Tag the function's return type with this uninhabited "phantom" type
because now you no longer have to remember from which argument some return value was calculated/derived: it's right there in the value's type.
[1] https://www.stackage.org/haddock/lts-12.6/safe-money-0.6/Mon...
Every time I start a new personal project I say 'oh neat I can use Rust!' N hours later (where N is a large number) I realize Go is about as fast, much easier and more readable syntax, and so I use Go if I want something that isn't Node. I'm a web developer so maybe Rust just isn't useful for that, but is Rust purely a systems level language for making super low level stuff? Forgive my ignorance, but what do people actually use it for where it outshines other languages?
Let's not get overboard here
That's very far from truth.
Rust does make guarantees about certain kinds of safety, when not using unsafe {} blocks. You get memory safety and freedom from data-race issues. I don't know if any other languages offer that without incurring runtime costs.
Slow rust code is also possible, but your code can't really be slow because it is written in rust, in the same way that c doesn't get in the way of performance.
Horses for courses.
Go has google behind it, so regardless of anyone's opinion they can very well jam it down everybody's throat through sheer throwing money at the problem.
Go was build for fast web servers, not for what Rust is aiming for at all.
Rust also has this this obnoxious issue around it that has become a meme :
https://transitiontech.ca/random/RIIR
Rust CAN be a good choice for building a bluetooth driver or writing the logic for pacemaker (oh god no !).
But it has the steepest 90 degree hill to climb mainly because :
- untested in the wild.
- lack of libraries.
- API stability.
You should keep on using Go due to it being better tested, unless some large company throws a few billion dollars behind it, its going to take a lot of time for Rust to catch up on its own.
I bet even by 2025 rust wont get much traction unless some bigCo heavily invests in it, do not take my word for it - just look at purely open source projects like FreeBSD, Linux took nearly 20+ years to get any traction.
Mozilla is comparatively not a financial heavy weight like google, Microsoft.
Google has a history of doing a million things that fail, but that is exactly what i mean. They can spam the programming community with millions of things and something will eventually stick. Moz doesn't have that type of financial firepower so for them it's Rust or bust.
This is a 100% false statement. Here’s a list: https://www.rust-lang.org/en-US/friends.html
I’ve been really impressed with how much success people have had with cross platform deployments as well. At RustConf we just saw a talk about one company putting Rust on satellites, doesn’t get more “wild” than that.
> - lack of libraries.
There are some gaps. But new libraries are showing up every day. For middle of the road, non-exotic stuff, I would be surprised if a developer doesn’t have everything they need.
> - API stability.
In the library ecosystem this is a small problem. In the past 3 years I rarely am broken from library upgrades. For the language though, I have never in the same 3 years been broken by a language upgrade. Not to say there haven’t been bugs that the language needed to fix, but stable has never failed to compile my oldest Rust 1.0 code.
Please don’t spread information ignorant of facts.
As for the rest of your argument: in many companies people is still moving to C11 or C++11. For many, software is considered for production only if it has been 5 years in the wild. A library appearing on cargo does not mean it is “available”.
However, from plans to actual usage takes years; specially for completely new projects using new languages, compilers, libraries, etc. in safety-critical stuff, that takes months just to validate.
Stating anything else is just either lying (marketing) or ignorance. Please do not do a disservice to your language by creating vacuous hype.
> For many, software is considered for production only if it has been 5 years in the wild.
Time is irrelevant, it’s about usage and stability. Every rust crate I rely on has published download numbers, which give you an idea of number of people using it. In that set, they are all open source and published on GitHub or Gitlab, so I can look at the codebases easily.
You can wait, that’s fine. But you do end up missing out on helping shape a new environment that is growing at crazy rates over the last few years.
If you think “download numbers” (or open source, or being in GitHub) is a good metric for measuring reliability, it means you haven’t really worked in any such field.
It isn’t growing _at all_ in many fields, because it is simply way too new (no new software projects started on it), it isn’t certified (or even impossible to certify). That does not mean it is not better, so don’t take that as an attack. It is simply a suicide in risk-analysis to use a new language, new libraries and new compiler front-end in safety-critical projects; so it is a no-go. Similarly for C11, C++14, C++17 and many other languages, frameworks and libraries that you have to approve.
I never have worked in such a field, and you're comments about certification, etc, are definitely things I will accept as true. Getting any support of new technology in any space is hard, and of course takes time.
But, I will say that "download numbers" where there is obvious sustained usage of a project is a stand-in for understanding if something is seeing real-world usage. I don't claim that it show stability, only that if it's usage is high and the number of issues on the project are not growing under that strain then you can begin to get a picture of it's stability.
When you talk about formal proofs, certification, etc. Those are different mechanisms for validating that, but generally requires substantial amounts of money to be done.
Facebook is too.
Amazon had a booth, I didn’t get a chance to talk to them about their current deployment personally.
Don’t underestimate China either, PingCap has huge deployments of their database, and while we may not hear about them often in the West, the numbers don’t lie.
I actually like the ergonomics of it a lot and have learned to satisfy the borrow checker. I would use it over Java for almost anything.
The biggest downside to me is the long iteration times when making a change, compiling, and testing repeatedly.
I've missed this property when writing Java and JS even before Rust was a thing, and Go has felt the same.
I appreciate it's approach to type safety and pattern matching, in fact, I find it pretty annoying to write code in a language that doesn't at least have sum types, pattern matching, and some kind of parametric/ad hoc polymorphism (Rust's traits feature).
Another nice thing about Rust is you can be pretty confident when writing multithreaded code. One of the slogans is 'fearless concurrency', and I think it lives up to that. I can write some little tool that does a bunch of things in parallel and know at compile time that I won't have any data races.
The tradeoff is that if you haven't written a lot of code in a lang with a similar type system, it can seem daunting.
From what I’ve seen, Rust prioritizes improvements in this order:
Refactoring code can be one of the hardest but most beneficial things a dev can do for a code base, so let’s make that simpler.
Reading code is done 10x more than writing code, so let’s make that intuitive.
Writing code can be tedious, how do we help make things ergonomic.
What this means is that the mentality of a weekend project, or any code you will write once and forget about is the worst way to try out Rust.
I’d recommend trying Rust twice. Once to create the first draft that might be shitty. Then again in a week or month to refactor that same code.
To paraphrase your question, you are essentially asking: "Why should I use language Y instead of X when X is fast enough for me, easier for me to read, and based on experience I like it better?" My immediate thought is that it sounds like language X is working quite well and aside from satisfying your personal curiosity there's no imperative to make that switch!
That's a tradeoff that bothers a lot of people who hear the Rust hype, only to find that it's more annoying to write the things they want to write. But if you use Rust and it makes a very hard thing possible, this is an incredibly empowering experience and you'll become a passionate believer. This is a dynamic that leads to arguments on the internet.
I've never done any substantial low-level systems programming, but there are high-level situations where I think Rust was better than anything else.
In one case, I simply couldn't get decent performance for something out of any garbage collected language I tried -- and GC time was the actual bottleneck. Rewriting in C++ seemed very intimidating and likely to be error-prone. Doing the same thing in Rust gave me the same benefits with the confidence that I hadn't made any dumb memory errors.
The second benefit of Rust is that concurrency and parallelism is easy, in the sense that 1) for basic parallelism, you can use Rayon without even thinking about it, and 2) in more complex cases, you can share stuff across threads and be confident that you haven't introduced any weird, hard-to-debug race conditions.
But sometimes it is not fast enough, and rust hits that sweet spot I need, offering both extreme speed (you can hardly go any faster in execution speed or memory management) and good enough productivity (something I can't achieve in C or C++ for various reasons, although they would be my second choice if I couldn't use rust for some reason).
So, I tend to use rust for not-super-low-level stuff (quite the opposite, actually), but this is somehow a last-recourse choice for me (I'd rather use go if I can, for productivity reasons).
> Explicit ! patterns make it easier to define what data a match will access. They also give us a way to use lints to help bridge the needs of safe and unsafe code: we can encourage unsafe code to write explicit ! patterns where they might help document subtle points of the semantics, without imposing that burden on safe code.