| I find Rust much easier to write than C. Its types let me be reasonably sure I’ve written appropriate code before I even get to the point of running tests, and I don’t have to memorize the flow of the whole program to have that assurance. For instance, struct Feet(i32);
struct Meters(i32);
fn hover(altitude: Meters) {
println!("At {} meters", altitude.0);
}
fn main() {
let altitude1 = Meters(16);
hover(altitude1);
let altitude2 = Feet(16);
hover(altitude2);
}
This fails at build time with: 12 | hover(altitude2);
| ----- ^^^^^^^^^ expected `Meters`, found `Feet`
| |
| arguments to this function are incorrect
Guaranteeing that I’ve never mixed units means I don’t have to worry about parking my spacecraft at 1/3 the expected altitude. Now I can concentrate on the rest of the logic. The language has my back on the types so I never have to waste brain cycles on the bookkeeping parts.That’s one example. It’s not unique to Rust by a long shot. But it’s still a vast improvement over C, where that same signed 32 bit data type is the number of eggs in a basket, the offset of bytes into a struct, the index of an array, a UTF-8 code point, or whatever else. This really shows up at refactoring time. Move some Rust code around and it’ll loudly let you know exactly what you need to fix before it’s ready. C? Not so much. |
``` #include <stdio.h>
typedef struct { int value; } Feet;
typedef struct { int value; } Meters;
void hover(Meters altitude) { printf("At %i meters\n", altitude.value); }
int main() { Meters altitude1 = {.value = 16}; hover(altitude1); Feet altitude2 = {.value = 16}; hover(altitude2); } ```
``` error: passing 'Feet' to parameter of incompatible type 'Meters' 20 | hover(altitude2); ```
Coming from a dynamically typed language (Python, etc), this might seem like a revelation, but its old news since the dawn of programming computers. A C language server will pick this up before compile time, just like `rust-analyzer` does: `argument of type "Feet" is incompatible with parameter of type "Meters"`.
Did you not know this? I feel like a lot of people on message boards criticizing C don't know that this would fail to compile and the IDE would tell you in advance...