248 points · by linkdd · 5y ago · 162 comments
> What's your favourite @rustlang boolean? Option<()>, Option<Option<!>>, std::iter::Once<()>, std::fmt::Result
> tired: u16, wired: BTreeSet<BTreeSet<BTreeSet<BTreeSet<()>>>>
> What's your favourite @rustlang integer? &[()], Enumerate<Repeat<()>>, Poll<File>, *const PhantomData<usize>
@jaaaarwr> How is Vec<()> not in this poll?
> That's just the owning version of &[()], right? Why would you need to own ()s? ;)
Edit: She's also the author of inline_python!, a serious macro for interspersing code that calls python (including local variable interop), and whichever_compiles!, a joke macro that takes multiple expressions, forks the compiler (as in a fork syscall), and compiles the first one that compiles to valid rust.
This is inspired.
> Did you know you can just fork() the @rustlang compiler from your proc_macro? :D
> This is, of course, a horrible idea.
> Unfortunately rustc is multithreaded and fork() only forks one thread. We'll just assume the other threads weren't doing anything important.
> In today's rustc, this means we're only missing the main thread in the fork. But that one was only going to call exit() after joining our thread anyway, so not very important. It just means the process always exits with a success status. So instead we grep the output for "error".
Any my favorite reply:
> Is this a rust implementation of autoconf?
https://mobile.twitter.com/m_ou_se/status/136863270144881869...
A lot of people are on board with not using if/else and instead :)
match x {
true => {}
false => {}
}EDIT: quoted wrong part of parent, ignore above
> match x { true => {} false => {} }
I really like this. Pattern matching syntax is great, nice to use in place of if/else as much as possible
There's a nice alternative though, which is empty struct errors.
#[derive(Debug, thiserror::Error, displays of::Display)]
/// Frobnicating the foo failed.
struct FrobError;
The advantage is the standard advantages types use, i.e. if I want to propagate it I know this specific zero sized type has a specific meaning. It'll also show a nice message if you print it. fn eject() -> i32 {
return return return return return return!!!!!!!!11;
}To clarify: the expression will run, but it has the type `!` ("never"). And while that's still not a "proper" rust type (other uninhabited types are though they may not be quite as special-cased in the compiler), it is in essence a bottom type: since it can't have a value, it will unify with any type.
That's why Rust is perfectly happy with
let foo = if a { 1 } else { return 42 };
The first branch has type `{integer}`, the second branch has type `!`. `!` unifies just fine with `{integer}`, therefore the typechecker is happy.Rust has a syntax called "turbofish" for disambiguating ambiguous generic calls. (Coined by Anna Harren on twitter, the first reply is an illustration from Karen Rustad Tölva, the inventor of Ferris [1]).
Although Vec is generic over any item type, you can normally just write
let foo = Vec::new();
If you're doing something complicated where the compiler can't infer the type, you instead use the turbofish syntax let foo = Vec::<u32>::new();
Some people hate this syntax. One of the better arguments I've seen against it comes (I think) from ManishEarth, who points out that it's very hard for the compiler to detect that incorrect attempts at writing a turbofish are in fact attempts at the turbofish and offer help.That test case (minus some excellent poetry) is
let (oh, woe, is, me) = ("the", "Turbofish", "remains", "undefeated");
let _: (bool, bool) = (oh<woe, is>(me));
That is actually comparing the string "the" against the string "Turbofish" and the string "remains" against the string "undefeated". The test case is there to point out that if the "::" in the turbofish is removed (Vec<u32>::new() instead of Vec::<u32>::new()) there will be cases where it's ambiguous.[1] https://twitter.com/whoisaldeka/status/914914008225816576?la...
EDIT: Fix my misspelling of ManishEarth
https://github.com/rust-lang/rfcs/pull/2527#issuecomment-414...
-- "The Humble Programmer"
https://www.cs.utexas.edu/~EWD/transcriptions/EWD03xx/EWD340...
A more elegant language that solves the problems that Rust solves, with a production-ready implementation and a good ecosystem hasn't been presented to the world yet. It's to be expected that if you want to benefit from its advantages, you need to pay the cost of dealing with a more complex language. On the other hand paying the cost of being exposed to more concepts pays off by giving you more flexibility to craft simple solutions. Complexity of a project can vastly exceed that of the language the project is written it. In that case the cognitive cost of using more advanced tools to manage that complexity is a boon in the long run.
This is analogous to any kind of more sophisticated technology, e.g. you can argue that a scythe is easier to use than a harvester, but with a big enough field, if you have the option, you'll go for the latter.
Practically, it's exactly what comes out of the infamous Rust vs. Go debate: for instance, the former prefers a short and concise albeit arguably more complex encoding and processing of the errors based on a monadic type, whereas the other leans toward a simpler, but more verbose, double return value + if/else/early return. Chose your poison.
He was right; there was a great future for that (and everything else in computing). But perhaps he didn't anticipate the FAR greater corporate appetite for functionality. The next feature is paramount. Who will code this next feature? The only path was richer and more powerful languages.
But this game's configuration requires us to play, compels us to play. And so we play to lose, to continue the game.
fn main() { break rust; }
This breaks rust =) fn punch_card() -> impl std::fmt::Debug {
This is a function that returns some type that implements Debug. Not specifically named.The rest of it is a combination of two syntaxes: .. and ..=
These are both ranges. The former exclusive, the latter inclusive. You can write something like 1..5 (or 1..=5) to get a range from 1 to 5 inclusive/exclusive, but you can also leave the start or end off: 2.. will give you from 1 till the end, ..=5 will give you from the start to 4. This means that .. will give you the full range. It looks more normal when used in context:
fn main() {
let s = "some string";
let some = &s[..=4]; // you'd probably write ..5 but i wanted to show both syntaxes
let string = &s[5..];
let all = &s[..]; // a no-op here but useful if s were a String and you wanted 'all' to be a &str
println!("{}", some);
println!("{}", string);
}
prints "some" and then "string".So, here's the tricky bit: you can overload what the range is over. They're not just for numbers. So:
fn main() {
let mut string = 'a'..='z';
let a = string.next();
let b = string.next();
println!("{:?}", a);
println!("{:?}", b);
}
prints "Some('a')" and then "Some('b')", because iterators return Options.So... all of this means that, you can implement a range of ranges. And so this string builds up a ridiculous unbounded range of unbounded range of unbounded range of ...
Rust has some type-system complexity to get your head around. It's not as painful as it looks (when you're just reading it rather than trying to do it) but there is a hump of understanding there that you have to get over. Once you've done that though, Rust then helps you so much more in dealing with the 'long tail' of difficult problems.
Another way of looking at it is that there are a load of things that you can silently get wrong in C++. There are good practices that help you not screw up e.g. you have to learn how to think about who has pointers to what and how long they live. Rust forces you to think about that stuff from day 1 - the compiler requires you to prove to it that everything is good. It's a bit painful to start with, but it's a good thing overall.
Np language can solve the inability of writing a correct program. Do you believe if your Rust program compiles it is free of errors??
If you get one.
In Rust if I overrun the bounds of an array I will get a panic. It is deterministic and specified, and the stacktrace will tell me which array I overran.
In C/C++ I get no such guarantees - the behaviour is explicitly undefined. If you are LUCKY you'll get a segfault there and then. For one off the end of an array that's unlikely, particularly if it's on the stack. You're much more likely to silently corrupt some data. The program will probably eventually segfault out, but there's no guarantee it's anywhere near the cause, and it could have done anything in the meantime. If you're on embedded it's even worse - no segfaults there at all.
No, if my Rust program compiles it is not necessarily free from errors. It is almost certainly free from memory errors though. Memory errors are problematic, hard to debug and the largest cause of security holes.
I'm not saying all the complexity of C++ is its own fault, but Rust shows how much of it is unnecessary. It manages without any constructors at all (think how many rules and features are connected to them!), without inheritance, and with only one (1!) way to initialize a variable.
Unless you write C++ like C with classes, which is not really writing C++ at all, Rust is actually simpler, easier to learn on your own, more consistent, with better compiler error messages, tooling, documentation, etc.
Your situation - boiling frog analogy - is a very common case but also the only one in which case C++ feels less complicated, simply because it's familiar.
Everything about C++ feels overwhelming, with so many decisions and degrees of freedom at every step, from build system, to lifetime management, mutable state, concurrency, and threading, to libraries, to dependencies, to deployment. It often feels easier, especially for beginners, because there are so many ways to silently do the wrong or suboptimal thing.
From my experience, it takes any new engineer, even if they have significant Rust experience, at least 3x the amount of time to get comfortable with a new Rust codebase than it does with a new C++ codebase. BUT, once you get past a certain stage of complexity, and everyone gets accustomed to the Rust codebase, managing the Rust codebase becomes a lot easier than the C++ one.
Personally, I agree that Rust is complex, but almost all of that complexity is inherent to the kinds of tradeoffs Rust makes. With different tradeoffs, I can certainly imagine a much simpler language, but it's less clear to me what stuff could be significantly simplified without doing so. However, I am extremely biased!
(In general, if you find yourself inventing falsehoods about other languages to promote Rust, you are Doing That Wrong, too.)
I have personally spent more time, summed over the past decade, preparing bug reports against Gcc than in debugging C++ memory-usage faults.
But C++ compiles faster.
Coding Rust is fun in much the way that Forth is: it is a charge to figure out a way to achieve a thing; you know it will ultimately be possible, and when you find the way, it is an ego boost. You could say, "Rust is the Second Programming Religion", and who could ever honestly disagree?
(But watch extremists downvote this to oblivion anyway.)
Works in what way? Serious question. Do you mean "works" as in 1) "doesn't crash/seg/overflow" or 2) "doesn't UB" or 3) "doesn't have race bugs" or 4) "does what the programmer intended"?
I would say from my experience, none are strictly true. I'll hazard you mean to imply the dev knows the language pretty well in order to satisfy "works lvl 1" but you still have veterans running into bugs of the 2-4 variety.
But even to get to (1), C++ requires a ton of domain knowledge. I've been working with C++ intensively for several months and incidentally for years, and I still seg every now and then. Even after using Valgrind, it feels rickety. Meanwhile, I've spent a few dozen weekends on Rust and I just feel way more confidence that my program will "just work" without crashing.
That's all still "level 1 works". When it comes to race conditions and programmer intent making its way into correct code, it's no comparison. Rust is way easier to get my intent into a running program. C++, I still have to lean into logs and debugging, because it just doesn't quite do what I want a non-trivial amount of the time.
It's not a religion. Rust simply is a better experience. I can say that having learned both basically side-by-side.
And even then, I think you're still behind rust. Sanitizers can only catch data races / memory errors / uninitialized reads / etc that actually happen. OTOH, Rust _proves_ that your program doesn't have these faults (modulo unsafe blocks).
This is actually something I agree with, even as a fan of Rust. Sometimes I wonder to what extent the appeal of Rust is based in the fact that you get to feel like a CS undergrad again, climbing mountains to make code compile and run
I don't believe this, but I'd love to be wrong. Is there an exemplary codebase somewhere that I can take a look at?
Genuine noob question: can you really compare Rust's borrow checker and lifetime management to the smart pointers in C++?
Some things only make sense if you know very old Rust, and they've just been updated as the language has been updated, obfuscating their original meaning.
[0]: https://github.com/rust-lang/rust/blob/69b352ef7749825abde2d...
[1]: https://github.com/rust-lang/rust/blob/69b352ef7749825abde2d...
Here are another couple of ways of writing the same general concept:
f({
return;
() // () in this case because f takes a parameter of that type
});
let x = return;
f(x);
So f() will never actually be called. You’ll get an unreachable_code warning on f.As a minimal case it’s mostly just funny, but the underlying concept does find its way into real Rust code, mostly in generated code (such as with macros). Also, although just about everything’s supposed to be an expression, sometimes things that can be an expression or a statement go a little bit funny, and return is a prime candidate for things going wrong in weird ways in the compiler frontend or in code generation or something, so it’s worthwhile having such tests (there will be more involved tests of return specifically elsewhere).
{
let x = return;
f(x)
}
where the call to f is clearly happening after an unconditional return.A slightly more practical example might be something like
f(if blah() { 42 } else { return })
which works out to, roughly, {
let x;
if blah() {
x = 42;
} else {
return;
}
f(x)
}
To get realistic, if you write f(g()?)
you basically get f(match g() {
Ok(x) => x,
Err(e) => return Err(e),
})
which is how rust does error propagation without exceptions and without constantly repeating a golang-style mantra.They’re always expressions in Rust, though they are often written with ; to make an expression statement.
There is also #![]. The difference is what they apply to, #[] applies to the following thing, #![] applies to the parent thing. You'll see #![] to enable nightly features in Rust, for example, and #[] for things like custom derives.