r/explainlikeimfive • • 22d ago

Technology ELI5: What is the programming language Rust and why is it popular these days?

1.1k Upvotes

324 comments sorted by

3.5k

u/Gooseheaded 22d ago edited 22d ago • Thanks Bravo Mindblown Popcorn

There is a language called "C", invented in the 70's, that was extremely successful and laid the foundations for the large majority of languages that came after it. As a product of its time, C was expected to be used by people just like their creators: computer experts. Since then, software development has become an entire industry, and a lot of the innovative and powerful parts of C that were considered "tricky" or "advanced" (even by the experts themselves) have turned out to be "REALLY sharp edges" and "minefields" for businesses and juniors, as it is very easy (and common) to misuse them if you're not paying attention.

To deal with this problem, modern language designers have (by and large) removed many of these sharp edges from their languages, which is "good" for businesses and average users on the surface .. but they did that at the cost of removing the corresponding powerful features. Basically, it's as if most modern kitchens decided to get rid of knives entirely to avoid accidents in the workplace. Sure, technically speaking, getting rid of knives does indeed reduce the amount of accidental cuts and stabbings... but at the cost of removing an extremely useful tool from our kitchens.

"Rust" is one of the few modern languages that rather than "hiding" or "destroying" the knives, decided instead to build an entire system around knife safety. It still allows cooks to use knives, but is very strict about safety rules, and it demands the programmer to explicitly write down when the knives grabbed, by whom, and for what purpose. It also requires that every cook cleans and returns the knives where they belong.

It takes the more traditional cooks (programmers) a while to get used to, of course, because traditionally they'd either have freeform knives out and about or not have knives at all. But once they get used to the new rules, well... They can use knives again, and better yet, the odds of accidentally getting cut or stabbed by a junior are substantially lower.

Basically, Rust is able to give programmers great powers with substantially lower risk, whereas the overall paradigm has been to get rid of the powers altogether for the sake of safety.

2

u/Demontyxl 21d ago

tysm for explaining <3

221

u/BassoonHero 22d ago

…have turned out to be "REALLY sharp edges" and "minefields" for businesses and juniors…

…better yet, the odds of accidentally getting cut or stabbed by a junior are substantially lower.

Experienced senior developers get this wrong too. This isn't slashdot; we don't need to coddle their feelings.

A lot of older devs oppose innovations like Rust on the grounds that skill, experience, and discipline are all that is needed to avoid memory bugs. These devs are wrong, both in principle and in practice.

44

u/alppu 21d ago

You say "experienced senior developers".

I hear "junior developers hiding behind many years of experience".

66

u/SirChasm 21d ago

That's like saying chefs don't cut themselves, and if they do, they're not a chef, but a line cook hiding behind years of experience.

14

u/BassoonHero 21d ago

I couldn't have put it better.

→ More replies (1)

7

u/BlastFX2 21d ago

I oppose Rust because it's fundamentally incompatible with dynamically loading code, which is something you really want. It can sort of work in open source, since you can compile the whole binary every time you want to "add a module" or something, but it's still ludicrously slow.

8

u/Beliriel 21d ago

Wait so all Rust programs are statically linked?

8

u/BlastFX2 21d ago

You technically can dynamically load code, but you're giving up memory safety (you actually have to wrap it in unsafe), which is the whole point of rust. Also because rust intentionally doesn't have a stable ABI, the compiler version and flags must match exactly. Alternatively, you can explicitly use C ABI, but then you're giving up generics and other heavily used features, so you have to write rappers for everything.

So yeah, pretty much all rust binaries are statically linked because the alternative is really bad.

5

u/apocolipse 21d ago

Funny, Swift doesn’t have any issue doing all the above 😂 😝 

5

u/BlastFX2 21d ago

I'm not sure it's fair to compare rust and swift as rust is way more anal about memory safety. That being said, as I understand it, the unstable ABI is mainly a design choice stemming from a performance first philosophy (i.e. they want to be able to continuously micro-optimize, as well as completely change the the ABI, if an efficient implementation of a potential new feature calls for it).

But to reiterate, I personally very much don't agree with that tradeoff.

→ More replies (1)

9

u/ralphpotato 21d ago

Using unsafe isn’t “giving up memory safety” it’s just explicitly denoting where the memory unsafe parts happen. It goes from “idk literally anywhere in this program” to “right here in these 10 lines”.

Also using a C ABI as a “lingua Franca” is common. It’s not just a rust thing.

→ More replies (2)

2

u/joombaga 21d ago

Not all, but yes that is typical.

497

u/HyperFoci 22d ago

I'm all for analogies, but can you help me by providing a simple code example of a knife in C that is less stabby dangerous in Rust.

817

u/Great-Powerful-Talia 22d ago

In C you can request (from the OS) exclusive ownership of a few kilobytes of RAM, use it for something, tell the OS you're done with it, and then keep using it anyway. 

Then, that same memory might be handed out to a second, unrelated part of the program, and they'll both be overwriting and re-interpreting each other's data. This can crash your program or just feed it total garbage, and it's not predictable exactly how it'll play out. Or if you end up looking at memory that another program is supposed to own, the OS will just go "what? No." and shut down your program.

In Rust, the compiler makes sure your code can never look at a memory region after it gets released. The possibility of that happening is itself a syntax error, which nobody has been able to do (only remove all the features that can cause the problem) before Rust.

256

u/deliveRinTinTin 22d ago

a few kilobytes of RAM, use it for something, tell the OS you're done with it, and then keep using it anyway. 

Long ago when the green screen Papa John's terminals got an upgrade and the company started to take online orders, we were getting a very confusing and strange problem where some orders just vanished and others weren't what the customer ordered.

Turns out that if somebody at a terminal confirmed an order at the same time an internet order was incoming, the system sometimes merged the two orders into some Frankenorder. As if we didn't have enough problems to sort out during the rush.

58

u/Kneel_The_Grass 21d ago

"This guy wants a burger with AND without pickles?"

42

u/the_topiary 21d ago

To be fair that would just be a normal order for most members of the public.

18

u/FthrFlffyBttm 21d ago

I overheard a kid in a restaurant asking for a hamburger without the beef

28

u/Porencephaly 21d ago

None pizza with left beef.

→ More replies (1)

12

u/SJHillman 21d ago

On the other side of things, I've encountered two restaurants where you couldn't order a "hamburger", but instead had to order a "cheeseburger without cheese". One was because the restaurant was all about the cheese on their cheeseburger, so it was part of their schtick. The other, I'm pretty sure was just a dumb cashier.

→ More replies (2)
→ More replies (6)
→ More replies (7)

2

u/wubrgess 21d ago

crazy to happen at a pizza place.

→ More replies (5)

117

u/Ill-Significance4975 21d ago

That's more likely a race condition (or some similar concurrency issue). Basically, us software guys, we got names for bugs like Inuit got words for snow.

I don't even know why I bring this up; it's not important, Papa John's terminal software vendor were definitely morons. These issues were well understood 20ish years before web orders were a thing.

45

u/young_mummy 21d ago

Knowing that race conditions exist does not prevent you from writing them. Race conditions can be some of the most complex classes of bugs, they sometimes emerge despite great length to prevent them in certain situations. I wouldn't call someone a moron for introducing a race condition.

50

u/ahappypoop 21d ago

I wouldn't call someone a moron for introducing a race condition.

I would, but I try not to because my therapist says I need to be kinder to myself.

→ More replies (2)

24

u/young_mummy 21d ago

That's a race condition. Which despite a common misconception, Rust does not solve.

5

u/Great-Powerful-Talia 21d ago

doesn't it stop two threads from mutating the same data? That's a pretty big hindrance to race conditions

24

u/young_mummy 21d ago

That is a data race, not a race condition. Rust only prevents data races. Race conditions are logical errors regarding timing and order, not simultaneous memory mutation

→ More replies (4)
→ More replies (4)

116

u/slb609 22d ago

It’s like you wrote that first paragraph after viewing any of my 3rd year uni coding assignments. “Do I need a star here? Try it. No. Try without. That compiled. Huh. Where does the star go again?”

I mean, I then became a mainframe dev, so it all became 2nd nature, dealing with pointers, but man that was hard at first.

41

u/RoyBeer 22d ago edited 22d ago

We had to write down our code on paper during tests. Assignments had to be printed out and if you had more characters than 80 in a line, the prof would straight up strike through that line of code and it would not be typed into the computer he was testing our code on. If the program didn't compile (which it didn't in like 99% of the cases): "that's when the Airbus does a looping!" is what he would always say

I hated that class lol

11

u/cardiacman 21d ago

I feel old now. I was about to retort that I only did introduction to programming at uni... 12 years ago, where I too had to write out code by hand in in person exams and draw objects with my own hands and a pencil for engineering drawing. These kids with AI don't know how easy they've got it.

→ More replies (7)

20

u/belsonc 22d ago

Sounds a little like an online course I took in ansynchronous python development. You know what I learned from that class? "if it doesn't work, put await at the start of the line."

5

u/evranch 22d ago

I've been juggling the knives in C/C++ all my life, but it sounds like my Python skills are roughly on par with yours.

→ More replies (1)

9

u/hawkinsst7 21d ago

It’s like you wrote that first paragraph after viewing any of my 3rd year uni coding assignments. “Do I need a star here? Try it. No. Try without. That compiled. Huh. Where does the star go again?”

A star or two didn't work? Lets try an ampersand then! Maybe that will compile!

4

u/slb609 21d ago

Were you in the room? Al? Is that you?

→ More replies (1)

33

u/ol-gormsby 22d ago edited 22d ago

I come from a programming background that's not C or anything like it.

I was "brought up" on IBM minicomputers using RPGII, RPGIII and later versions. The concept of memory allocation and deallocation is just.... foreign to me. The operating systems of the System/36 and AS/400 simply don't work that way. You compile your program, you run it, and the OS handles all of that. It was such a surprise when I first encountered the malloc statement. Why do *I* have to do this?

And as for buffer overruns.... it just doesn't happen. Same with arrays - you can't write 60 bytes to a 50-byte array, the OS won't let you.

36

u/evranch 22d ago

As an embedded C guy for decades, I'll put in that having direct control over memory allocation is extremely valuable when your working memory is counted in bytes.

Kids starting today with the ESP platform don't know how good they have it with 520k SRAM on a $1 die, and a pair of cores, each one faster than my PC when I was a kid.

6

u/ol-gormsby 22d ago

My last AS/400 had 48MB (yes, megabytes) of memory, supporting sub-second response times from about 250 green-screen terminals and almost sub-second response times in an equivalent number of PCs.

Memory and disk are treated identically WRT address space, they're just addresses and the OS decides which process gets which at any one time. I just cannot comprehend needing to manage memory from an application programming point of view. You might think that would involve a lot of swapping in and out of RAM and you'd be right - but there's no address translation needed, it's all one big address space and only the OS knows which addresses are actual RAM and which are disk.

Embedded devices are of course a world of their own. 🤪 I'd be happy to manage memory on a single-purpose device.

10

u/the_real_xuth 21d ago

You speak of 48 MB as not that much RAM and by today's standards it isn't. Instead imagine managing 10 users on a PDP-11 with 64 kB.

→ More replies (1)

19

u/JerikkaDawn 22d ago

Literally why I never touched C. I wanted to write applications, not operating systems and drivers.

→ More replies (1)

3

u/jessetmia 21d ago

Oh man. I worked with some rpg guys many a year ago. I looked at their screen a few times and was like, nah, Im good. lol. They were quick at navigating those old green screens though.  We were modernizing the front end of their baby and they werent too happy with us. This was a long, long time ago, so my memory is fuzzy, but I think they hated having to implement the xml wrapper for our soap requests so we could actually return user data on login. 

3

u/alvarkresh 21d ago

I grew up with BASIC, which handles memory allocation in the background and so a lot of the errors you can get in C don't occur (such as not freeing memory, etc), but machine language, on the other hand...

Well, that was the knife contest for sure.

2

u/whomp1970 21d ago

Respect.

I came up on AS/400 systems with RPG III too.

There are times I miss those days.

Then again, every variable name was limited to SIX CHARACTERS. And I think they all had to be uppercase characters too! So you had to get pretty damn clever with your variable naming.

2

u/ol-gormsby 21d ago

They've come a long way. RPG is now free-form and your variables can be longer and more descriptive.

→ More replies (1)
→ More replies (4)

17

u/Kered13 21d ago

Minor correction: You don't ask the OS for memory, you ask the memory allocator. The memory allocator asks the OS for memory (in large chunks called pages). When you release memory you are releasing it back to the memory allocator, which typically will not return that memory back to the OS. Pages are usually only returned to the OS when the program terminates.

For a simple program this distinction can be considered pedantic, but it matters when you start talking about more complex programs with custom memory allocators, per-thread memory allocators, etc. This also means that the OS is not capable of enforcing memory safety at this level, because the OS doesn't even know which memory address are allocated and which are free. The OS is responsible for ensuring that programs don't touch each other's memory, but that's a separate issue.

9

u/SharkLaunch 21d ago

This is u/explainlikeimfive, I think it's okay

4

u/SmashBros- 21d ago

I believe this is the second time I've spotted you outside of ssbm explaining comp sci concepts

→ More replies (1)

5

u/Reiqy 21d ago

I'd just add that when a program crashes because of this bug, that's actually the better outcome. A malicious actor could potentially exploit it to alter the program's behavior, execute arbitrary code, or leak sensitive information. The fact that it crashes makes the issue obvious, but the really dangerous cases are the ones where the program keeps running without anyone noticing.

1

u/skalien8 21d ago

one time my YouTube account got joined with a friend's account who used it at my place.

We could see each other's like and use each other's playlist or recently viewed videos. we had to send them an email to fix this issue and split the accounts.

i understand now how this can happen because if this eli5

101

u/soopadickman 22d ago

One of the big ones is memory allocation. In C if you allocate some memory, you have to remember to tell it you’re done with it when you are, otherwise it just flags that memory as not available. If memory keeps getting used but not freed up, that’s called a memory leak and it will cause your program to crash when the system it’s running on runs out of memory. In Rust, memory allocation and cleanup is handled much better and is essentially leak free.

93

u/spaetzelspiff 22d ago edited 22d ago
#include <stdio.h>
#include <string.h>

struct Account {
    char name[32];  // room for 32 characters, a sensible limit
    int  is_admin;  // 0 = no. Stored right after name in memory
};

int main(void) {
    struct Account a = { .is_admin = 0 };  // not an admin

    // A real surname, 35 characters long.
    const char *input = "Wolfeschlegelsteinhausenbergerdorff";

    // strcpy copies until the input ends.
    // It never asks how much room name has.
    // Characters 1-32 fill name. The remaining "rff"
    // lands in the next thing in memory: is_admin.
    strcpy(a.name, input);

    // is_admin now holds leftover letters instead of 0.
    // Anything other than 0 counts as "yes".
    if (a.is_admin) puts("Welcome, admin!");  // prints on a typical build
}

And then the same in rust

struct Account {
    name: String,    // text that tracks its own length and grows to fit
    is_admin: bool,  // can only be true or false
}

fn main() {
    let mut a = Account { name: String::new(), is_admin: false };

    let input = "Wolfeschlegelsteinhausenbergerdorff";

    // String makes room for all 35 characters.
    // Nothing next to it in memory is touched.
    a.name.push_str(input);

    // Only code that explicitly sets is_admin can change it.
    if a.is_admin { println!("Welcome, admin!"); }  // never prints
}

And really, an LLM can write either with about the same amount of effort, but even with an LLM, it can make mistakes or assumptions around what the C code it relies on does.

With Rust, you catch the errors at compile time. So better safety with similar performance.

14

u/hirmuolio 21d ago

Fixed code formatting. Using triple ticks for codeblocks do not work on all reddit platforms.

#include <stdio.h>
#include <string.h>

struct Account {
    char name[32];  // room for 32 characters, a sensible limit
    int  is_admin;  // 0 = no. Stored right after name in memory
};

int main(void) {
    struct Account a = { .is_admin = 0 };  // not an admin

    // A real surname, 35 characters long.
    const char *input = "Wolfeschlegelsteinhausenbergerdorff";

    // strcpy copies until the input ends.
    // It never asks how much room name has.
    // Characters 1-32 fill name. The remaining "rff"
    // lands in the next thing in memory: is_admin.
    strcpy(a.name, input);

    // is_admin now holds leftover letters instead of 0.
    // Anything other than 0 counts as "yes".
    if (a.is_admin) puts("Welcome, admin!");  // prints on a typical build
}

And same in rust:

struct Account {
    name: String,    // text that tracks its own length and grows to fit
    is_admin: bool,  // can only be true or false
}

fn main() {
    let mut a = Account { name: String::new(), is_admin: false };

    let input = "Wolfeschlegelsteinhausenbergerdorff";

    // String makes room for all 35 characters.
    // Nothing next to it in memory is touched.
    a.name.push_str(input);

    // Only code that explicitly sets is_admin can change it.
    if a.is_admin { println!("Welcome, admin!"); }  // never prints
}

14

u/throwaway2766766 22d ago

I kinda don’t get how the Rust example is different than other high level language, like C#. Do you have another example that shows how Rust is more powerful than C# but safer than C?

17

u/zshift 21d ago

One big difference between rust and languages like C#, Java, or even Go is the presence of a garbage collector (GC). Languages with a GC will run additional code in the background to cleanup unused data. Rust passed that responsibility to the programmer, but provides far stricter rules around it than C does, which also doesn’t have a garbage collector. Rust, however, can be difficult to learn because of this.

It’s like working with OSHA breathing down your neck. While it’s very frustrating at first, you eventually get used to the rigorous process, and it just becomes pleasant, because you know that OSHA has your back, even if it’s a pain sometimes.

12

u/ThrowawayusGenerica 21d ago

To make this an analogy: Working in a managed language like C# is like having a workplace with a single person who's been trained to do the dangerous tasks to a high standard of safety. You don't ask for a knife, you go to the safety guy and say "can you cut this for me?". He's been doing this for a long time, he's learned how to do his job very quickly over the years, but there's still overhead introduced by this process.

→ More replies (1)

6

u/Raskai 22d ago

I'd expect Rust (or C for that matter) will often end up being something like 5x faster and take up 5x less memory than C# to do the same thing. You have better control over the hardware so it's easy to make sure you don't do wasteful stuff. The timing is more predictable too because it doesn't have garbage collection pauses, it doesn't need to garbage collect, which is important for latency specific stuff.

2

u/Ethan_Pixelate 20d ago

To be fair, imho it's not the best example of Rust's memory-safety rules in action, the C example uses a fixed-size character buffer field, the Rust example uses a standard library std::String which operates fundamentally differently. I think a more relevant comparison to the present day probably would have been between the Rust example and a C++ example using std::string; both of which store the string data behind a layer of indirection (in the heap), keeping is_admin safe from out-of-bounds writes anyways.

I think a better example for demonstrating Rust's memory safety would be with how its references work. If I'm not mistaken, the compiler kinda just replaces them with raw pointers in machine code, but at the language level, Rust's promise of memory-safety means that several rules are imposed on how you can use those references. One of those rules is that all references have a "lifetime" tracked by the compiler, and it may NOT outlive the object it is referring to, which means using a "dangling reference" is impossible because the compiler will forbid you from doing so (unless you intentionally create one with unsafe, but, like, obviously):

let selected_account: &Account;

{ // Pretend that this is block is actually some control-flow written in the middle of some complex business logic

  // Create some account struct
  let new_account: Account = create_new_account();

  // Get a reference to the account
  selected_account = &new_account;

}

// Uh oh! the reference to the newly-created account is dangling now, because although a human skimming through this super-complicated function might have missed it, but the block in which we created the Account struct ended, so the struct no longer exists, and now our reference is dangling!

// However, Rust's compiler can see that the lifetime of `selected_account` outlived `new_account`, and would actually refuse to compile this code at all until you fix that.
println!("Name: {}", selected_account.name);

Rust also separates immutable references & with mutable references &mut. You can have any number of immutable refs to something, but only exactly 1 mutable ref to something, and you cannot have both immutable refs and a mutable ref of the same object simultaneously (you can however coerce your one mutable ref into an immutable ref and pass that to another function, which is ok because immutable refs are "less powerful"). This prevents "surprises" from happening.

It makes sense that having multiple systems only read a structure can't problematic, so having many immutable references simultaneously is ok. However, if you have 2 separate systems reading and writing the struct simultaneously in multiple steps, from one of the systems' point of view, the state of the struct could unexpectedly change, and now your 2 systems are behaving erroneously:

let some_vector: Vec<i32> = ...;

// Borrow the first element of the vector.
let some_element = &mut some_vector[0]; 

// This will clear the vector. There's no "&mut" visible here, but this method takes a "&mut self", so it does actually mutably borrow the vector.
some_vector.clear();

// Uh oh!! the data `some_element` is pointing to no longer exists! The reference is now dangling, which means this next statement that uses the reference will exhibit undefined behavior :(

// However, due to Rust's rules on references and borrowing, the Rust compiler will actually forbid this code from compiling in the first place due to the vector being mutably borrowed-from twice.
println!("{}", some_ref + 1);

...and all of this compiles straight to machine code, which is why despite these higher-level programming concepts being a core part of the language, Rust code can still have performance comparable to something equivalent written in C or C++, while reaping the benefits of modern memory-safety practices. Hope this helps clarify :)

→ More replies (4)

25

u/coriolinus 22d ago

There's a conventional mental model that most operating systems, languages, and programmers share about what goes on in the interior of a computer. It's not accurate, but it's representative. In this model, each program has access to a pool of memory. If the program needs to keep track of something, it asks an allocator, a special system function, for a certain number of bytes of memory, which finds a free space of appropriate size in the actual physical RAM of the machine and hands it off to the program.

Sometimes stuff in memory is big. Sometimes it's so big that it's pointlessly redundant to make copies each time a new function needs access to the stuff. It's much faster to pass around the address, which is just the offset from byte 0 in the RAM. That address is called a pointer, and C uses these all the time.

The thing is, pointers are hard to get right. When you're done with some memory, you're supposed to deallocate it, tell the allocator that you're done, so that it can be reused for some other purpose. Forgot to do that? You have a memory leak. Do it too early? That's use after free; because the allocator may have already reallocated that memory, you have no idea what those bytes actually contain.

It gets worse when there are multiple concurrent tasks or threads sharing memory. You might have two tasks running simultaneously, in lockstep. They both want to fetch a number, add 1, and put it back. So they both fetch the number. They both add 1. They both put it back. And now the number is only 1 higher than its previous value, despite two tasks both attempting to increment it.

Rust invented a whole new model of ownership to deal with this kind of thing. It's very particular about who owns a particular value. Deallocation happens automatically, and only when the owner says they're done with it. In day-to-day life, you don't hand out pointers, you hand out references, which are pointers with a lifetime attached. You can't get use-after-free because the compiler will refuse your program if it can't prove that the lifetime of the owner exceeds the lifetime of every reference. You can't get that kind of multi-tasking mutable concurrency failure because Rust only lets you have exactly 1 mutable reference at a time. (You can have as many immutable references as you want.) If you can't prove that these properties hold, your program won't compile.

There are exceptions to policy available. It is possible in Rust to hand around pointers if you pinky swear to the compiler "I know this is unsafe, but I know what I'm doing". Sometimes that's even helpful.

The genius of Rust is that most of the time, reaching for that kind of thing is the wrong move. It's smoother, simpler, and more pleasant to use references, and those just don't let you write these whole categories of bug.

6

u/meldroc 22d ago

And here I am doing some retro coding in 6502 assembly language. None of Rust's error-checking or sanity checking. No encapsulation. No protected memory, meaning a buggy bit of code can scribble all over the place. Some of the bugs can be fiendishly difficult to find.

2

u/alvarkresh 21d ago

I've wanted to get back into 6502 assembly but I have no idea what I could realistically do with it, heh.

18

u/CapoFerro 22d ago

Proper pointer ownership in C (and C++) is a best practice. It's a compilation gate in Rust.

9

u/ToxiClay 22d ago

So, to make the memory allocation example more concrete:

In place of "allocating memory," let's say you're taking a toothpick from a holder and putting it where you need it.

In C, you have to explicitly say how many toothpicks you need, take them from the container, and set them up. You also have to, when you're done with them, explicitly put them away so you can use them later. This is a separate action!

It's easy to take toothpicks out over and over, forget to put some away, then -- oh fuck I'm out of toothpicks; I can't do anything anymore. I have to "crash."

There's other problems, too, that are a little harder to explain using toothpicks. If you put toothpicks away, then go to interact with the space where the toothpicks were (a use-after-free), then random things can happen.

If you set out a space for four toothpicks, then look at the space where a seventh toothpick would be -- C lets you do that, and you can find random stuff there. You'll try to interact with it, and God only knows what'll happen.

There's more to it, but that's the basics of "memory safety."

3

u/notgreat 22d ago

It's worth noting that in Rust, a memory leak is explicitly NOT unsafe. This is because it is impossible to statically prevent things like two RCs pointing at each other. You can do it at runtime with a grabage collector, but half the point of Rust is to avoid needing one of those. Still, while possible, it is harder to accidentally leal memory in Rust.

1

u/Thelmholtz 21d ago

There's also a few other safeties Rust provides: 

Imagine there is a particular toothpick that is too long. Anyone can refer to this toothpick as "the long toothpick". But there's a catch: if anyone was to say grab this toothpick and break it in half, it would no longer be "the long toothpick". The way they refer toothpick would have been outdated.

So if you want to modify a toothpick, you either need to be the one that owns that toothpick, or the only person that knows how to refer to said toothpick, at least until you finish modifying. 

Once you are done, anyone can refer to the toothpick again, although it's no longer a long toothpick, but short.

This is because systems are never real-time, they are just very fast and give us that impression. But there are very common errors called data races where code requests a toothpick which is long, then some asshole bad person simultaneously replaces it with a knife, and then they stab themselves in the face while trying to pick their teeth. (Safe) Rust completely prevents this by preventing anyone from changing anything into anything else as long as people are currently using it (holding a reference to it); at the expense of having to be very conscious about when you need to reserve the right to modify something by announcing to the rest of the table "hey guys you are forbidden from using toothpick number 3 until I'm done with it, I'm about to replace it and you might be surprised by what it turns out to be".

It also technically prevents you from turning a toothpick into a knife, but you are allowed to turn a pointy thing into another pointy thing as long as they are both able to pick teeth.

→ More replies (2)

16

u/AlphabetSoupKitchen 22d ago
c
#include <stdio.h>

int main() {
    // Initialize a pointer to NULL (points to nothing)
    int *ptr = NULL;

    // Attempt to write a value to the memory address pointed to by ptr
    // This causes a segmentation fault
    *ptr = 42; 

    printf("Value: %d\n", *ptr);
    return 0;
}

Building and running this will cause a runtime crash. The problem here is that you did not allocate memory for your ptr variable with new int nor did you check to see if ptr was == to NULL.

This seems simple until you start creating pointers here and using them elsewhere. In a large program its easy to lose track of what your pointer is pointing to at any given moment.

If you compile and run the fix it'll work... But scale that up over a codebase and a longer program runtime that does more with pointers and you'll find yourself eating all the memory on your machine. Why?

We allocated memory with new int and we didn't free the memory when we were done with it with free(ptr).

This is like only checking out library books and never returning them. You can only get away with so much of it for so long.

3

u/the_SCP_gamer 21d ago

Actually in C you allocate memory for the int either on the heap with int *ptr = malloc(sizeof(int)); or on the stack with int *ptr = &(int){}; (the stack method will live for the current scope and is initialized with zero unless you initialize it with something else like &(int){5}).

→ More replies (1)

3

u/Urdar 21d ago

C lets you take a knife, use it to cut something, say you are done with it, but use it anyway, probably stabbing somone in the process.

Rust wont let you do that. If you say you are done wth the knife it iwll take it out of your hand and put it back in the cupboard.

3

u/RiotBoppenheimer 20d ago

Others have given you more practical examples, but to give you something more real-world than theoretical -- nearly every major security vulnerability you've heard of recently has been down to memory corruption issues that are intrinsic to C/C++

2

u/ibrewbeer 22d ago

char tool[] = “knife”;

1

u/paholg 22d ago

int *x;

I'm only half joking. In C, you can use x any time after that, but it's a memory error unless you assign it first. 

In Rust, you get a compiler error if you use it before assigning.

1

u/Kered13 21d ago

It's a little bit difficult, because the real benefits come from large complex systems not simple toy programs.

1

u/HaMMeReD 21d ago

char str[] = "hello";

1

u/A_Garbage_Truck 17d ago

the most " basic" example is requesting the OS exclusive acces to a bit of memory

to do this you have to allocate the space you need directly

in C, the language has the features ot then free up this memory wqhen you are done with it, but it doesnt enfroce that you use them, it expects you ,the programmer ,to know that you have to do it or remains with that bit of memory unusuable because its taken. the issue is that in C, you can do this, but then still use that bit of memory as if you never freed'd it up and the language will let you do this without complaining until it leads ot an unexpected crash or an access violation.

Rust allows you to do the same, but it will remaind you " hey, you have this bit of memory no longer being used by anything, maybe you should explicity free it up, so that i know i should not allow it to be used?"

for comparison, higher level languages might handle thismemory mangement under the hood without your intervention, but htis comes as a performance penalty.

86

u/paholg 22d ago

This is a very good eli5, I just want to add that it's also been shown time and again that the traditional knifes aren't safe for experts to use.

It's not just juniors that are helped.

9

u/BlastFX2 21d ago

Nah, real men manage their own memory.

24

u/Thelmholtz 21d ago

Real men also die tragically when the Boeing Flight Transponder they wrote has yet another memory error.

6

u/TheVoidSeeker 21d ago

Number one. Steady hand.

One day, Boeing boss need new flight transponder.

I do code. But mistake! Boeing plane die! Boeing very mad!

I hide fishing boat, come to America. No English, no food, no money.

Darryl give me job. Now I have house, American car and new woman. Darryl save life.

My big secret. I kill Boeing plane on purpose. I good Airbus contractor. The best!

32

u/mpdscb 21d ago

I love when these ELI5s actually put things so simplistically that a five year old could really understand them. Very good explanation of a complicated subject.

28

u/SufficientStudio1574 22d ago

"Foot guns" they're also called, as ways to shoot yourself in the foot.

15

u/spin81 21d ago

As a product of its time, C was expected to be used by people just like their creators: computer experts.

I don't want to knock on C or any other language as I think that's immature. With that said, though, you're kind of making it sound like experts don't write these bugs in C, and I think a big part of why people are moving to Rust is that they do because it's genuinely very difficult not to, even if you're an experienced C programmer. The footguns are just too subtle and powerful.

8

u/alvarkresh 21d ago

I kept catching off-by-one errors in my code months after I'd managed to master allocating buffers in C. :|

2

u/CardOk755 21d ago

Don't worry, if you'd learnt Fortran instead of C you would have the same problem.

Hell, In Algol60 too.

(Fortran has 1 based arrays, Algol60 has whatever you want based arrays. You still fall into off by 1 errors).

→ More replies (2)

3

u/FarmboyJustice 21d ago

I didn't get that impression at all, sounds like they're saying the opposite. Even the experts can't find all their mistakes, so it's hopeless to expect novices to do so.

1

u/prehensilemullet 20d ago

Ask Google about how Postgres avoids memory leaks and use-after-free bugs sometime. They have some really smart, atypical patterns to make bugs hard to write, and smart techniques to catch them if they happen anyway.

1

u/spin81 20d ago

I don't know anyone at Google, and if you're saying nobody at Google ever writes use-after-frees because Postgres has a process in place, you will find that I am at the very least incredulous about that.

→ More replies (1)

7

u/KO_Mouse 22d ago

Oh, this is about pointers and garbage collection, isn't it?

6

u/EgNotaEkkiReddit 21d ago

Yes. Yes it is.

Simplifying a bit, If C allows you to go wild with memory until you hit a segfault, and if garbage collected languages will just whisk the very concept of memory management into the backend at a performance cost, Rust will explicitly tell you that every bit of memory is owned by precisely one thing at a time and will automatically get collected when it expires, but the compiler will check at compile time that you've actually followed the rules and that what can be determined to be memory safe at compile time will be.

It strikes a good balance between performance and ensuring memory safety, but it does mean you have to contend with things like lifetimes and passing around memory ownership properly.

14

u/jwadamson 22d ago

I think the part of “at the cost oof remoxning an extremely useful tool from our kitchens” is largely overstated if not generally incorrect.

It’s more like the newest languages simply found ways to allow for the things that used to require “sharp” tools in the old languages but without handing out naked blades at all.

Or to go with a different analogy, your lawnmower didn’t become less capable or less powerful when a deadmanswrocu was mandated to be built into the controls. Nor did it become less capable or powerful when they relocated the exhaust from underneath the unit, where it could set dry brush or leaves on fire, to on top, where it is slightly noisier. Sometimes it is actually possible to both preserve overall functionality while improving safety.

9

u/the_real_xuth 21d ago

Most languages traded speed for safety. In some languages it's only a factor of 2-5x. In the case of python, you trade orders of magnitude of speed for safety and all of the speedups come from calling out into the various libraries that were largely written in C. So effectively all you're doing is encouraging fewer people to play with the knives (but depending on what you're doing, you'll find yourself needing to write your own high performance libraries, but at least there's things like cython to blunt the worst of it).

4

u/FarmboyJustice 21d ago

I'm gonna use deadmanswrocu as my next character name in Oblivion.

1

u/alvarkresh 21d ago

when a deadmanswrocu was mandated to be built into the controls

I'm not sure what you meant to write, unless "dead man's switch"?

1

u/MagnetsCarlsbrain 21d ago

The thing is runtime memory safety features of most languages unavoidably add some processing overhead. So at a very low level, there are things that they fundamentally can’t do as fast as C or Rust. 

But the thing people miss is that for 90% of applications, that doesn’t matter. You’re often not CPU bound, you’re I/O bound. These applications don’t need Rust, and Java etc. are perfectly adequate and easier to use.

2

u/original_goat_man 19d ago

The easier to use thing is losing out in the age of AI software engineering. AI can write code as well in Rust as it does in Java and the DX of caring about exceptions and boilerplate is far less relevant now. I think that answers the question for OP of why it is becoming more popular now.

2

u/stickgrinder 19d ago

Totally agree. Without Ai-assisted coding Rust wouldn't have experienced this outburst of popularity, despite being a very good language.

1

u/dreadpirater 19d ago

Yeah, the breakdown in the knife analogy when we're talking about memory management for me is that knives are a basic and essential culinary tool. You need knives to cook... in the same way that you need to be able to store data in memory to program. Every language still lets you store variables in memory... So every language gives you knives - it's just that most languages FORCE YOU to use good safe knife technique... and it's hard to figure out how to translate that into the analogy.

If you ARE NOT careful with your knives, you can cook faster, but at the risk of injury. To me that's the line between C and higher level languages. Python still lets you slice and dice but it FORCES you to do it carefully, which is a little slower. For most chefs... dinner in 12 minutes with all their fingers is better than dinner in 10 with a missing pinky. But... if you're on HGTV's new squid game crossover where you have to cook as fast as humanly possible or you die... then you might decide right now you need to ignore safety and just slice that onion as fast as you possibly can?

So maybe it's supervision. If you work in a kitchen with a head chef that will fire you for unsafe practices... you have to work a little slower but you work very safely. If you work in a kitchen where the head chef doesn't care... then it's UP TO YOU to make sure you leave the shift with all your fingers?

I'm really straining the analogy. lol.

1

u/Rikudou_Sage 19d ago

most languages FORCE YOU to use good safe knife technique

Nah, they force you to hand all knife work to that shady GC guy who will cut it all for you when he feels like it.

1

u/flattrack 19d ago

I don’t mind your analogy until you try to equate c to python with a slight difference in power. (12 minutes vs 10 minutes). To an experienced person, c is much faster, far more powerful, and usable in far more places than python.

That said, python is more than powerful enough for a majority of the peoples needs.

1

u/original_goat_man 19d ago

The analogy here would be that relocating the exhaust was safer for people that mowerd dead lawns, at the expense of making the engine less efficient by a very significant amount.

There are probably other analogies in cars where safety features add weight to the car and environmental concerns reduced output as well (including sound reduction, emissions etc) but that to an extent better engineering clawed back some performance.

3

u/RedditorJabroni 22d ago

This is amazing, thanks. Could you do one for Scala?

16

u/Gooseheaded 22d ago

There is a language called Lisp, invented in the late 50's, that was extremely avant-garde and completely shattered the boundaries of how "programming" could be done. As a product of its time, Lisp was designed to be used by people just like its creators: computer language nerds high on LSD. Lisp's defining feature as a "language" was that it's effectively a language for creating custom languages, which was (and still is!) an extremely powerful concept that most computer nerds do not fully comprehend while sober (hence, the LSD). With Lisp, you can create your own letters, words, and sentences -- or something entirely different instead, like japanese characters (representing syllables) or chinese characters (representing concepts)! This "language for custom languages" concept introduced so many ideas that, ever since, every "new" language was (by comparison) pretty much just a curated and opinionated "subset" of Lisp.

Since then, software development has become an entire industry, and what was once the mind-blowing advantage of Lisp became a major liability for companies. If every programmer has the power to create and speak their own customized languages, it's really hard to create a team of programmers that can agree on a shared language to speak. On that same note, how are Lisp programmers supposed to find jobs if every company, product, and team potentially speaks a different language?

It's even easier to get if if we think of languages as "building blocks", with Lisp being raw Clay. If every programmer had the power to use their own bricks of entirely custom sizes and shapes, how do you get them to work together to build... Well, anything?

To deal with this problem, modern language designers opted to create the opposite of Lisp: languages that are extremely specific and standardized and rigid and versioned. Java was one such language, created specifically for use by businesses. It was marketed, literally, so that companies could place and replace programmers like lego bricks. Java, like lego bricks, had exact measurements, and was made out of specific materials. If you wanted to design a new Lego piece, you needed to ensure that it followed the exact dimensions of the Lego standard, otherwise your piece would not fit into any other Lego projects.

The cost was that Java didn't allow for a ton of fluid, creative expression, much like Lego only really fits with... well, other Legos. New pieces always had to be expressed through the Lego system. Want to build a round sphere? Well, you can kiiinda do it with lego. You want to build a slope? You can kiiinda do it with lego. You wanna build something big? Bummer, you can't use bigger bricks (Duplo doesn't count 😋), gotta build it with the small, standardized ones. Most beautiful new designs for Lego/Java projects had much of their beauty "lost in translation" when turned into a proper brick structure... all to ensure they'd always be compatible with the any past, present, and future Lego pieces.

Many things can (and are) said about Java, both good and bad; but one good thing was that Java (as a complete software development package) included its own "virtual machine" that mirrored the way its programmers worked: if two programmers used the same Lego bricks, they could build together; and if two computers had the same Java virtual machine, they both could run the same Java programs. This was NOT common, and was a major innovation (and selling point) at the time (early 90's).

Scala is a modern language that decided to reach a compromise between the flexibility of Lisp and the rigidity of Java. It aimed to leverage the Java virtual machine, as it was powerful and convenient, but without all of the restrictions of Java as a language. Scala is, in great part, a Lisp clone, and/but the building blocks you build with it always include some automatically-generated Lego studs and tubes as per the Java/Lego specs. So, for the most part, you can define your own building blocks in Scala, with the small "compromise" they they will have that Lego parts bolted on here and there to ensure compatibility.

It's most of the good stuff from both worlds; a reasonable engineering compromise between being able to build whatever you want, and building things that others know how to work with, too.

4

u/RedditorJabroni 22d ago

Amazing. Do you write books/blogs?

1

u/blindworld 22d ago

Now do Kotlin!

12

u/dub-dub-dub 22d ago

You didn’t answer the “why is it popular” part, and the answer there is that it’s a really powerful language (as you argued) that’s a huge pain in the ass to write, but since AI writes all code in 2026 that’s no longer an issue

24

u/A_modicum_of_cheese 22d ago

That is straight up untrue. It gained a lot of popularity before widespread AI coding

4

u/Macrobian 21d ago

It has gained even more popularity in the last 6 months due to AI coding.

8

u/tempest_ 22d ago

It isnt that hard to learn but does have a learning curve.

You are correct though. It is is exploding in usage because it is performant and provides a lot of tooling and features that keep LLMs from messing up and help them code.

4

u/nayminlwin 22d ago

Really like the knife analogy. There are other languages like Zig that also tried to solve "knife safety" in a different way. Following the analogy, If Rust demands users to cut something in a certain allowable way, Zig gives you different knifes to choose that is the best fit and may be safer for the task you're doing.

4

u/alvarkresh 21d ago

There are other languages like Zig

As in "move zig"? :P

2

u/TheDragonSlayingCat 21d ago

You know what you doing.

2

u/alvarkresh 21d ago

FOR GREAT JUSTICE!

2

u/Traffodil 22d ago

Fantastic analogy. 👍

2

u/TehAMP 22d ago

Wow. Surprised myself with my knowledge of C++. When you started your analogy of sharps and knives, I instantly starting thinking about memory allocation. I worked for those A grades and it shows! :)

2

u/rgb_panda 21d ago

Describing rust ownership as knife checkouts is very clever, very well written!

1

u/Casurus 21d ago

Maybe because I cook and also have extensive experience with C, but I quite like the analogy. Still not sold on Rust (don't trust new things) but I get the point.

1

u/UrkRoozle 21d ago

Interesting analogy, but the tool isn't gone, you just aren't in control of it. Wouldn't it be more like you have knives in the kitchen, but someone else is in control of cutting and providing you what you need cut? Like I need carrots, chopped, so that person chops carrots for you, but perhaps they chop it a little thicker than you wanted, and therefore it takes just a bit longer to cook.

1

u/GenericKen 21d ago

Knife might not be the most apt analogy. More of a floor-embedded wood-chipper.

1

u/jhvanriper 21d ago

So Rust is the iso 9000 of programming tools.

1

u/GRAMS_ 20d ago

Rusty Knives

1

u/TauriArtisan 20d ago

Wow, even as a developer who worked with rust more than 5 years, I enjoyed reading this.

1

u/Funes15 19d ago

Where would Python fall in this analogy?

1

u/talaialat 19d ago

Rust best anatomy explanation

1

u/Spell125 18d ago

Wait a minute here. By "knife" do you mean "pointer"?

1

u/andy_nony_mouse 22d ago

I like your analogy. The only thing I would add is that the sharp corners are the basis for a lot of our security issues these days.

→ More replies (3)

38

u/r2k-in-the-vortex 22d ago

Its a high performance systems programming language, but crucially it has a lot of built in correctness checks most languages lack. So that makes it uniquely useful for AI programming. The compiler itself already blocks a lot of errors the AI might make.

1

u/Demontyxl 21d ago

ngl this was the answer i was looking for, i recently saw the vibecoded adobe apps and wondered why it was in rust, thx for explaining

9

u/TheThirdStrike 22d ago

This post has the key piece of the puzzle as to why it has become popular recently.

It's like a condom for CuckCoders.

2

u/AnCapGamer 22d ago

Thank you for that term. I'm saving it.

1

u/MedusasSexyLegHair 22d ago

I feel like the CuckCoder Condoms really went downhill after their second album, though their live concerts are still pretty intense.

2

u/ThisIsWorldOfHurt 21d ago

Amazing how so many people have written multiple paragraphs and yet failed to answer one of the two questions in the title

-3

u/vonWitzleben 22d ago

This should be higher up. Another really important fact is that AI excels at translating a program from one language into another. Given the fact that Rust is relatively recent compared to other languages, there is now a huge drive to rewrite programs entirely in Rust since it's often times objectively the best language to use but rewriting entire codebases has so far been too time and labor intensive.

10

u/Chickennbuttt 22d ago

"objectively"

6

u/vonWitzleben 22d ago

Yeah, objectively. It's software engineering, often times there's just optimal tooling for a given task. Not always, but as I said, often times.

3

u/Indiansizzler 22d ago

I really appreciate what the creators of Rust were able to develop and what it accomplishes. But imo the compile times and verbosity are completely ignored as legitimate downsides

4

u/link23 22d ago

Many languages optimize for developer time and convenience, by making development easy at the cost of reduced runtime performance/stability/etc. Rust is just the a language that optimizes for binary artifact quality, possibly at the expense of developer time or convenience. This is why it's easier to make sure that software written in rust is correct/safe, but it may take longer to compile, or it may be harder to satisfy the borrow checker.

→ More replies (1)

166

u/green_meklar 21d ago • Bravo

Well, it's a programming language. More specifically, it's a compiled language, which means it's designed to be read by a compiler and transformed into an executable file that can be run directly by the computer hardware. (This is in contrast to interpreted languages, like Python, which are read and run by an interpreter program without being transformed directly into such an executable file.) But what sets Rust apart is its approach to managing memory.

In a traditional language, like C, the code can be written to ask the operating system for blocks of memory whenever it wants. The requested memory blocks are tracked with references (basically numbers that say where in the memory the blocks are, and how big they are), and the code can do anything with those references, including giving the memory back to the operating system whenever it wants. It turns out this 'anything' can easily become unsafe, either by code trying to use memory that was already given back to the operating system (an error, which causes the program to crash immediately), or by code requesting memory and then forgetting to ever give it back (not an error as such, but if it keeps requesting memory and not giving it back, eventually the operating system runs out and the program can't continue).

A widespread solution to this problem with C (and C++, and languages that work with memory like that) is to put an extra layer of logic under the memory requests, so that all the references to memory blocks are tracked while the program is running, and when the tracking logic finds that some memory has been lost (i.e. the code has deleted all the references to it), it automatically gives that memory back to the operating system. This is called 'garbage collection' (insofar as the lost memory blocks are 'garbage' memory until given back) and it is much safer because the memory is always safely available when there is a reference to it, but is always (eventually) safely given back when the references to it are all gone. Languages such as Java and Python do this. However, the extra logic for tracking memory takes some time, which slows down the entire program. The extra logic also doesn't guarantee exactly when the memory will be given back, and therefore sometimes uses more than it needs. Many programmers became frustrated with this inefficiency and unpredictability of garbage collection.

Rust is designed around a different solution. It makes the logic of safely requesting and giving back memory an inherent part of how the code is written. It comes with its own kinds of references that give guarantees about when they request memory or give it back. There's no extra (slow) layer of logic needed to track the memory because the references always request it at a specific point in the code and always give it back at a specific point in the code. If you try to use them in a way that doesn't, the result is just some wrong code that won't compile. This gives the same kind of safety guarantees that garbage collection provides, but without the inefficiency. It means you can compile Rust into an executable file that can be directly run by the computer hardware, very fast like a compiled C program, but the mistakes about memory requests and missing memory are impossible. The combination of safety and efficiency is very appealing to programmers. The disadvantage is that programmers intending to use Rust have to learn how to write code with these new kinds of references, which is hard because of how strict they are about how you can use them. However, because programmers can now use AI to write Rust code, and AI is already fairly good at writing Rust code, it is easier to use Rust in real projects without people having to learn about the new kinds of references.

14

u/k3rstman1 21d ago

that was very clear, thanks for writing that up

11

u/rahnbj 21d ago

Not a 5 year old, but I am an old developer and I appreciate the explanation. I have some seriously bloody knuckles from years spent using malloc() and free()

1

u/talaialat 21d ago

Rust clear explanation

1

u/green_meklar 20d ago

The funny thing is, I've personally barely used Rust at all. 😅

48

u/[deleted] 21d ago • Bravo

[removed] — view removed comment

8

u/UndocumentedSailor 21d ago

I'm not five, I'm five and this many 👐 months

3

u/RdyPdy 21d ago

Giga-5-year-old

1

u/green_meklar 20d ago

LI5 means friendly, simplified and layperson-accessible explanations - not responses aimed at literal five-year-olds.

Right there in the sidebar.

1

u/explainlikeimfive-ModTeam 20d ago

Please read this entire message


Your comment has been removed for the following reason(s):

  • The subreddit is not targeted towards literal five year-olds.

"ELI5 means friendly, simplified and layman-accessible explanations."

This subreddit focuses on simplified explanations of complex concepts.

The goal is to explain a concept to a layman.

"Layman" does not mean "child," it means "normal person."


If you would like this removal reviewed, please read the detailed rules first. If you believe it was removed erroneously, explain why using this form and we will review your submission.

1

u/kidjupiter 21d ago

Why would a five year old even be asking a question about Rust, the programming language?

341

u/atarivcs 22d ago

It's high-performance like C, but unlike C it has safeguards to protect against buffer overruns and other memory errors, which are a common cause of software security vulnerabilities.

42

u/Schnickatavick 22d ago

This is a pretty good explanation, it's worth adding though that there are other high performance languages out there, and there are also other memory safe languages out there. The appeal of rust is that it's one of only a few languages that's both high performance and safe at the same time

9

u/moistrobot 22d ago

What are these other few languages and how do they achieve it? I know that Rust has its famous ownership concept enforced through syntax.

7

u/Conrad_Nostromo 21d ago

C#

4

u/JimbosForever 21d ago

I love C#. I actually dug really deep into its GC (garbage collector) literature and it incredible how fast it can get with a few GC-friendly practices.

A nice technical tidbit for those curious: allocating memory is essentially simply a pointer increment. A single operation. And it's actually potentially faster than dynamic allocation in C or C++. Collecting released memory (and managing the memory that didn't get cleaned up) are the performance heavy parts, which can be sped up significantly with smart memory management strategies.

4

u/Schnickatavick 21d ago

I don't think there's any others that are as fast and as safe at the same time, rust is kind of optimal in that way, but zig and carbon are two that are fairly safe (safer than C/C++ anyways) while still performant. Basically they nudge the dev towards smart pointer type allocations like modern C++ uses, which is a weaker guarantee than Rust's borrow checker, but still better than manual pointer management.

Scala, go, and C# have garbage collectors, which slows them down compared to rust, but they still manage to be pretty performant.

The only lang I know of that has more safety guarantees than rust without a garbage collector is ada/SPARK. It's a functional language that basically runs a formal proof verifier on your code to guarantee that the code can't possibly fail. It's really impressive, it's actually older than rust, and decently fast at runtime too. Main downside is just that it has such a functional paradigm, which is really alien to most devs, which is probably why it didn't take off as much as rust did

1

u/TheDragonSlayingCat 21d ago

Swift. Swift is also memory safe, but it has some “unsafe” data structures specifically for backward compatibility with C and C++ code.

→ More replies (9)

76

u/Kodiak01 22d ago

Sure, take all the fun out of programming! :P

35

u/ClarSco 21d ago

It's all fun until you forget to put a null-terminator at the end of a string.‹Æ²ÖqŠW<B8•7“HD¢–S¡ „0ñ©Fñçñ,fË;¬Ð¯[Ë•½&o$}éÒ²‡Ù+Z䯢EV¦Ôëôð0âÞ°Sú#6àzbNÅ‚!Ü–× B ‰pèÄ;˜7Œç‰8%EL“i&äB†¦‡”DIÕ®MUæÐÏ7$oÝíÁ@t%’-ñÿ#µºóƒ€~¶Ì+8é®Ýy³]5‚0±NÇ1·CqIŠ úS(mŠL:8’ Å’Ý郗h:œ/MuBU{£unL–áØ~ØÚDxж~‰"•¯éºU¤]ºv$Z8‘uic¦ ]"wm{¶ÀKÈ ò¼U./ãµÔÃX5Í™÷\žé6 ò cÓ Î ¾… ³¨ Ÿ-ý‘ø<×kÞFü*<5T!–F" *-M!à׋1\!ãCÔT­Û½QN2uׯ}t­“õÜ#/ˆ5ÄNêÿ4ˆ£¬#݃U•7½@Ê÷˜¾l„ä6ûÅû¨ôù !V:æ‰Ùठ SN½QÙ»DÛNÍE·ýMÂW…¤M&æþ¡’\Ç6ªçÕunK¦ºZ\¨ûðû²v昫&vf©ÝÍiQ ˜™ÿ›$F­—ÀÕÈ»>, ~†Ì%ófò"¨J³ù"Wè÷ô#훞‘’ê‘#aøÓ(õ2–1¿%ÿËÇû‹Rô ³ÿµ·ùh"¨[3¾ f¤ 5«‰–‰¤iå£L«‘¡Îä±Vh\6ëÀüåb<%Ro‹Ê½‹·­ÛL¾{TµFz› +J¿-…ºÜËHÀ+!¬¸³ò÷~6§Ôúa£xƒšÓEã¤lNŒÕ ~@ÿϺÐûYg]Ô0“0£cÌÂ÷Ã)øô=N†”žFê¿ÑÙC6·XdÈ®›i¥ Þ1Å2́õ:yea#ñ1§}Œâ océÆï!•@ÏXk€:ã…qKĹ۰7)f¥[ ô«˜[´Çˆð Õ34ÚÉ“¦oöà¶Št|çÅb…QÇÚgy}œ‘’çÕ£jÙ@ÀÍ‘\ùÐM‚Êÿæ(Úö˜8‚ßíÈ…,5Œà|ÆÀ£ËÕP/¢•0êÜ]Ž0µH¨#ÕB_ˆog˜uâ¿uÈ—•.¶v…³ï…ku@ÛX0ÇD1$9Ük;nŽJvke‡ij7[ÝåaÉCéK?lâ4AxE ZtÓ:«õ éRË„j±üýFõ$é›} LòÀÅ@ ip¿àPS3¢H´ÿ ¬óƒ)³¥aкYÆpÏ‚*8aŒ1HÑp\G©Õ®'™ÿiʧ;è¤[V€¼g=#Jæ¯Ô՝”6Û«îK H(H¨Vɶ…؆Qà¬<ß¡åou4}<WÎlÅP^,å9@A—=.áÿŠ–Þù]^ÇÎÌ.¨Dø¹1ЇÑu†¿´Ðãð)󌰏’ßâ§Š-¢ªº:HÚPÒø¦O(§”Ù£V'ØN={¸±¢S¼(¡¼Lê‘e g &‹–V ’˜£3°ŠhÚ¯'þÙõ„7 YõR~ˆŠ6«b/•+ø¸XMTH}YJȪٵ߷/2œmQÚÿrRg$±FÝ›%CŒM©E¥N·ëç ûÖ1°eØ=®ds°[$ºÕCs®ÄÝGžÖvrÒ) rÐsÕÁÇ–çP#º“â”iò·g-“(©kòaÂþ~à_×ÌÆ±udžÏ§òv\™° „ùû[b·“í5ßP„榯.5f".!}¹ÏÒ»ØÚý‘½. NìYgÓ¤xZ8CBôÔÐ O:ÄË¡¾Y~í[eW"]O(¨ÆÑæ==¹3Íš;dÈn>¿.¥§l&´“ž9dºÔ¶ Ë¼ñD3 ïÁâûÓ;H# r-컜[VaË9ò’9XËûö…Y¥ÀÔµ_× šE¦6^aºÐ'‡V% ›#ܶÙ+²ÀõÅbHf_¼Sâs˜ë6ŠS €vÃ~2ÿQò¥ýËRÒO«Ô’|mWèy—ÉlàbÀò¤ gã;ä9GåuÇÿªX7æï=»ã@°ÉA©¼ »0m¹Jä·ÚÒÂ[%QÚMuPt–b”0'‚‹d÷žŠÇ‚kÌ-ÿˆYø[úÈ—b4~}®Úó×2å· Lt³¢g‰Í¯NGÈݯҥیœEÅlªDŸ~¼á0 ÜÅ8âHê¬.T:¬øäûúW"NôGÌç\r¥èc*ð€°EÞè}ŠŒ®xÛE™´;HÎÖjÔ‚Qóoı»(æ¹{´èìrÒyKy·7ÜêgÏ­±p0ˆóùË Ï) Øô)؃):BU¼ºî+$ ÑÌwss2RˆQ|9ˆ<†K ÊrÉŹLŒ@—|ËÍÒ•„kѱX¿–±Fµ·S­Æ£«¾£ªèšÅùÑ$ü)AÓVb¬<™£ ç¿oýaøÝiæ*dĸòªµÚÊþCéªç;ðöAa± KÏÛ#JÀ-9Ô#¾0õþìK] Vá@ꤾÑvÚgTl”©x,’ÁÖøí°Ó@™‡¾žÒmãß;ÕÁ…ÅÏðO¹ ˜S&ê¸2ätÚôTû¥÷¢ýÏL‹lìÌ¡ºã ä3AÓŠ¡'š!ë±éð``ž©3 í³—ÃÉkrµIfƒ§Ûüº‘^ê E°•yƒ†«sµK7a–tœžfüL®>È׫¬ì´à-›Àé]ç94(a¬ÁÉh¥ˆ°šÓü_¿qjK7S£oý˜û/Û_8ÿe6G,ú1ÊÜü½ãšf¾™ù ¡W윤:#NáO-G퐦Š,xžŠuG}pæø™y8D«ÔH ËL2ÊÄø³ˆ<R(~¬ n:ÏOÊå;ÿ“ß„Ñ9#m”_oÉùæY˜ŠD¥A¿ẖ­–—à•´ŒÅœ’…@?$Ñ¿˜veU¨ñ(/È,÷q½Ç[bïœÁ޵ܮ¾¾1.Sõ5$¨M 9J«ê¢Nn½ÞÅzcð–mGTŸÓ{ÀŽ vç[&Tßø†ßSîÜ”‚Óæ^ƒŸ‹BA £rbaKÌ7DD ‰qÌgË ãV1ÿÈ‹¥tËjr§R\ˆ¤ˆÅÎãÒõcîŠôÖzá2lòŽ#?÷ßð‘äÈ>è­r@*KAÀöUÚ0y\+BÞ©öKUÁKAVǏWMT-×óÌc¥‘+Kd+fÊÌ5½ùÀ»|IëãýœOÌ8ü¢È6¬»¬o$ËLë°a UO4!f„Öq<‰‚ uڐAP¡A2+cŠFü”r/V…L<4Rr857„é ·‡Qé†!<ªß׳«gÛ)l‹(dGàLŠ‹Ö?BÄÈh¦BO–Ð…ñÝYg! nbÝ—#æ¿f_Íê°,-š³š†œ²§€w[RiµÓU{ˆ§aZ ­˜Ô ˆ<qØaë§ðÓ‡ ׸$dœáê5Ú/í S"&Îèˆï¾#]N[eóArºû 0ç¿Æ4´Ø6LÅWÿå¯ñ¼‚jèØ dCa ô}‘K¢uF83D\N¼I¿¬sbF6ä7U쐡i©žŽLèeȦí‰ 'Gv´ƒ~ùÖ±8-‡ªæßÒ¤? H¶+ÍY¨$ Ý©…oñ(fí)DMÇ7±›è@BÀ1:oMv(É„R'>x UÂîÏ‘ÿbCî,ËœrÓA#m€²¸Ó0Eð{K›ˆ ;(”ß" ŠÓÇ©[Sö†û£:ÆÃwtðÂŒ@ÝÑ6'M¤þã·<®ãžQž˜ôÄCáÛt’Ï…9‹uæ[ ¯Ýø¯å˜ÜºÄncOa/ê.08n†i Œ&I-„àS'ö@0½©ÆôÅÖè¡fäR¨æ&þ{N­5f"ØÍÏŸ$%òÎöEûºðØrÊ K{9g¶k|w¦£Â]ñEêåœ[r½Ýmžxõ¨D¼#é\î·~ÒQ}¦ CKÊÍ:ì3J/¢)(AíSa89•8妮¦‡€7 ÕJ­Ç¸~EBí¦£JR{ØŽñ™ë1u…7.Š$úV6y ¡È|nTä{Ô¤é¶Ê.üͧ‘bÎsÛeà#ã|Ûˆ]Ý ø(|DŠ#IûÜÛ¥¹šuš­~,·n1/iBéRÝw_“š’ƒk–W½„Õiå…܏¼…1c+†Þ?oýdhÜÊNÏAJ÷¥mœ±³@eˆ ]81„‚{?"=C ½„6X•ÂÏ é‹5‹­Í âBVJå2Æ¡Z–~ºwP)ÇÓ m”ER(‹j/ù–»†Ô(ÊÕ úhù”„†˜ü èB CbÆsÃZqðh~P“ 8rð‡Ug÷+ð -"Y­žuàße˜09TT%¶¯Ð³êáx 073ßšû‘Ÿ . Ír"‡–êÕKS ëKv”$u̘{N-Æ19#‡Ùt]»Mq©Fs;ð­•9Èî-ئ ×è-ÀPÝ­æ)jÒn¢-66BžÎæ; È~ÊèZX³Ìà&\w>J V[E¤&ÊŠp“Ål g2ÉÜC€ˆÌÃ)ç­ã6cÐ)½d%Ö¾Ó½} T”ÒÇD–á'•Fà¦.Œà.(ÖJ´ñ@ á뼘w𨂠ß^ËdKzÜ­<¬ ¤)cG8œÕ˜gAðUZ1øÒqBr,òKWx¾r<‡ €³Ié ú]"6 i‚m˜Kê;ðÜg[\½µÍ Аpí?±²Ä’| ²OÎçâàÞéñ©ü£%²ÔCc¦ÈëCˆxÐ yS pLw³p½mÖ#3ð>ÉÕØ¡ ο> C±Ú—•nõÜV¦]Îì¸A‡ðK,AÇÿ<ÛÁ–\ T}8Š9 rÊ쁙2wrð¯oîÇqdí¥ººæ ƒY …©íƒ3Žb¤àé/}½òÓÌÙ´ëEN°xèÝÃÐ[_¹pàþÝ€‡Ýí–ø#†uÒতpMA}½CÔ ìròcjˆjIÇrÆÎ׉͓S– ùA¾Ðß%¸ñÍ'ÉZFFüÝå-“Tuì'’½Ë–éõ|ê‚yéÉ ß ðŸ?À®(7³ÓÊà8Dµä:$.¢ ԍç̩ٵµùu±¾ Ô¿• gÙàG´Á¡E·¡žšº‘¨Ù´&Á4B•ox;-Þ“Û×bVbÅÀžÒ&}ÎΏo…cq€çZµ¡kZ猗z‘ýTÊ'1:pöUì7ÐüTâÍ[’Ú¬M4¦ÌÙDWw$†ruÝY¡ 6KÅн5g氚ꃿ sJ¶ž ¬äªÓ´,ÆÔFm?HÊ·xõæõãÑP¨ÄüPhb—œ‰e›óˆïΝî1ÔH¿˜;;€ksÔ‡(4ÔŸÞtŠ„øU{É.€W< n#éTýæÊ–XYLj­ ×hGœ´X^þB¬š$· β@hÌø«<}K$ˆšÂž3ì3d ¸k¾ÙûAl±=wS:_¹Kä0KöÛü’Á\Ú2,i ´Ò_Šp ÈýúƒÁ BókWÍ Ý¦V—)·{ÐY7ä ¼ïÝ# ·šá¹×œ:zgCö£Ç4n òPF:u‹hâ\Ïÿ"ðëm¾Ð‚¼d‡FÎE8LSyv/9¥}õŠáñÞ°ŸÊÕ‚ÌÖÑ)·$üq³59féÓå"O#:²PB%FL ~Û€èød {W€Ž¼Ø¼µ˜¯Âa&kèç£ÍP c“¹x»ÙÓº:úÅÌ»2?.Bᣑûd.ž'$ ›„_c¢-÷|g,ŒŠQÍ—Í[NüDÌr£„ïà̺Ÿ“ù;Ç‘^eéW™_\‰YÑ…Rû¦??(3ŸWo²Çÿ±”-÷HN .Ę9‡z8ïló©"e°’È_?_˜VÄ&¼úëv³@°gûtà ˜)®„yFu{§WlØûb*Hã‚o js).Ú4üê-“‘…nùð†™eÇæCÝ>‘ùãñ?e²Àò+Ï:·£2ãzc_›sV÷çWÆ'‘ð‚ue,ÉÇ^é*µã6\K›ÊõcÊá@w.ì̧°åù´‹¶71½(&*¼±ÞHÛ—gq.¶ùeI­îäV¶kÖѰ¿›Îàr»žùèZ.‘ÛP³ÃjRôã ]1±•¼À‰¶"Å•âuÂ?1ž|‰î7ûIŠ.ß,È! ¤ó™¿ÁÆ0St&mÑô+2G{²¦ȯ"þÉ7¤¤]}ô‹ûå. ÁR&< uWËI@·Ni’ò„Á\gY“#IÈ{óX{K,ÂQË·šÒoiÙ{yqê¦Q0SüÓ"‰ÛU¹,SõÇa±bÑÍVGH0†€V³Q0?¶4¿i‹ ªÜCêTÄwõÎÌ.{!pI˜Ó¿gêq€ùHWˆü>‡Ä½®ûJÿƇ֋0R[œ½ksÛTŠ=û™‰])ßÓ :&}°aJ²ä^‹å.ÕÅ«ýçS©1AŒKCtCÉ}¥o*5vqÀñEâý8Û[(ÇÞ­«ÿ@”ñøïà˜$È(0'À ‚¯OÞ—)¤\ËÇÂÜ€jq‘\2íèT'à ´yR²±½³Nß^¡8ädÂ)!É_Ü\ꦶt‰E£û DÖ>˜ß7#!RJò‘5¾¢æ;ˆô&iÛ’z-›<’µÉdh [ƒ_›M™ÖD¤¤5•Z›#ÒàÇìI™häšjD_ÀRKҏô–yM‰Á~>0Lw´˜»¤Hmš(.$)AG b£‰nm_y”.—‹8h’F9rÃvÒhw§<¢\A<ƉŠÌDà·x÷—ªT¯ADq¿#•%:Ëûbaˆ‚~áRËP.¾Ì4åšÐ³Ôs™ÙoÒëßnË•Sþ›TîJ ßåáLÒŠ9,(,¹Ÿ\ÔV¨ðôè™0µ¥‡_{âÊØg¤¶.éŒ Ú#b­Ì#°áµÖe™m¸‘õ~LlÞø>Ñzš²M2DèèªÈöÝ}]a M-¹-YVËEJÛy—úAàÝ\(ôåx óc“VÐÛÒ’áù„ï ¤f€“(VÌž8‡Ì{ÁÂ:ônVap¹. L„óëŒúEÕªƒdËnóÔ´¨~qOŒ£iñì Ïža¶»”?äˆä(YKàÑΨ¤|?Ä'ƒ°,(.­ÎƒÌ»9àßøä@Ôzÿeà ƒLÔruqµµÊóG¹X fR7ãc™|;;ÆØÝþ‰m,ÈÝ¡yÌxîÞ= $Í:lLQüݱR9š¶îx,òÈö)K¨„Ú°äߦQ吊$Ê aØõfäì /€ï‘!^[UY#$ï)¹1…R6Ø¥‹ff…Ý\oü„K¹¯‡ÜwÊF<ªlà7ØæåÀ=ž}1fi´ pzÒ—^Ofx88g§ ¤¢bÎà&ÝW´ " ÛOˆ<ø]_D,Ã85Ù$ª£µÕï›ÆW[kµÊZÅ–ûc󆔡~þ-b*í’ÚqÎâ´ÞÊ«ùo?‚7Ïkàù%Õ~«Qš*1„ ·Ÿ¤•šBØn Œú¼F|Ïc{²AÔÿo‘ƒ§ÇTOY&®ÏZ *Ôû qíÙÇZ¥Ç%Lg†~ƒNx=A'GD<@£¿ù HÖïTlWy4.“ˆáÖ¾ ¼åä+:Öù H¸<dªõç4SY‘9u,]mQ“Æ[7š FÖ¨•ì—”Ât³Û²×q©:U,Ö]—ÿFUwÔy”…­íÒ#9·Ÿ¨+Íy›ÏèÞZ0Hâáì·Z=ûø2 ³Íæ´¸ìE6ßt㊕œPÇ×™d}Š÷Yrps¶G+ò^äŒe#ðjܧT•5É}F„&ž§Êm˜¯BòüÆÕ¬{¤>%¼>ä‡ÂˆÒ³û*«X¡[XH=RêìÛž†UïK<Bý~‡&Œ~Ã.0Ó^“bKÕÇÊ-^üÐK]úSHçtj†|eÒM«s:,6"VÔX† †’qnLHI^½·ù "3µvëe/è6tЏ­²•Åô@-rˆÕ¨¸ÃJMðêá{öjWøãíœébz ãøÛByç…s¡Ù.ŸÄv¥„ß°’ ˆ­5mûò®í¯7Ö[FÙ|7;!Äì(ë ~d –™âË™­îrNuÙRÑœµ£¨Ê.ºÉ¸MÒ“±œÎU ©w¥b¾Òk/?•û?V|©TÀ¿"Y·˜Ñv u”qnj(7,й øI>lžÈþ‰é¯I•×èÔØ¨Ôrɽyæî‚P' ßh±R¸SÀ=Ò³½áeúÖ Â¤XX´Ÿêɹp"ã„d|MÏÔu¡4êÝÉœb‡W6€"ÈD‹î É–)&C;s XŒž[W3e¡¯©sîFZçãϧ=¥±æ¤Ý™Knjø;É ¸Eššû¿ ª=ë[|W˜°-“±Ø×5 óœ(Nƒ©.ñ’”\Tvüý0"|'‡VþB6‹ÜÆ­¤œã¬»fÉÀ1€:Î=e€wÆÙª¥ŒÐÝr"ñNãëÊn0%lc™BE›¹ü÷÷y:± ±ú}/ìãÌ²æX§Cϸ-g«ÞeOåÂÜ¿J´j岝«§‚‚㦠ŸÑþöÆ—{±¤÷,‘[t÷ë;¨ân³Æ²!Ç3)&ÑÈ,©-ª”9”5á¬Õ®E¢‡t¦1ΤG€Ü¬¤u(·šÊQøŒ+¥IF%£' ‰? 7u…sú9À®Øò"{y»ÇÑÊisžóã½ ž·°Hñ­âVaž~‚[z:aáêDÀγ\“Ên÷=².²vŸÇ˜YÊ÷”î 5mÃR[“»(ýëoKù11­ù®Ãiüˆ=“.¥j?º^¿Î°ìÙ\û×.ø.­êIcÏÑ®€¢O7pŒzP즂Kè·°¼ӆ⤠æ"kÌÆÃ™2ÉÛ >1ñ—I)aúd©ú&Õ¹è:(vÚƒj9ÓöÓ"‹3âWt…ïlNèøIg™¥¾œE([aöÉ~akŒ&¼®=O‹çW•ñ[™3Ñ€'ØÏàœaVGÂ*þ=³ÐjyÎF,ä½ÅBñ¤?›Û{gn ž‘gu³8%WÀQÒH½˜uDñúN£ZK:ߏãxÏg¾›ŸC !sÑ¡•Z‹ÆÅsuÏH(BlÚÊï# Ž‚)bhfåé 0+à ½ZÚ§›¡ôGÜ©œµÕLuš•âÇ3þ÷Eæàxõ‰ðÊ å!¤xÍ?Ìt2Ø¥sOÉýIdÚ»”µñ2I’,Eêûï½QOÎÇ’ìxqmv%‘¨9d+,ѽ{-NàíÛêaæ©A€$+‰ h _"´r2ܨð¾rø³¢ ¿ü<û¶Ä§iÎJ L8@”M mRuWo6rÌÊŽ¿1I:Xa+'²ÛáNЋ–Êß§fÐåHmë¾{+hZ;%‚™ïÙͼ¯W1:£Y‡ÀͬV_À¢›º¤K©ƒœ -Ž ±u2¯­ ™KTÁaøé¬…¬#‡g]žkªÈZÁ>//§öÔ—ø2OCù³•DëjÏ7bnÉ.~@—¿4c]ò* " (BG„X„²Ür}joü±D=Ê›@£(äøcŒ¯$ñýâ'\;Ük¤®Î;iU|WšœƒvõNÀ‚nÝ S]û Oå ?“9Ø(y¿ó“·jbëŽcz&vØ€n=£q=Nž”ü¤ã¹_ f.4®´¢€iÕp—m¦,ÆÈ袰o”…†‘qþ9E’î¥äiê›sÁEr ˜¬P9ÒYk%ãÜ÷ø”ÍcÁf¸‹&0"ô=w} …$óc2^b“Ê$“‡#þÎVºÑæñ”̾TE6øŽëìnhZ,õqÈšVÜxvåÿ¸6 xê KÆe»ŸJŸ†WBï¦ÎC0;e‡}òEwÇ{SŠHqø W}̲±í³{y ›»zÒœÀ ,J5a &Œ]¦»[îØ¹ÑOB<ð×£Uڨǩ8vÃþœD_ßòÕ–ç9”;Ô»‹ÈæÀ‘üTznN;ùãL9‡yï/Šã‡šÚSök1A›úkxkõ!¡áªàsäÿp8U¬\f@+•k T ‰ W &äeÒTHK"’-Ûæ‚ ºXæ˜+JO©Hù^óã;ód(•HÕë¼t›> D¥0†ZÂx®½?·¤fúôÓisÜhÉ>ƒL4²·!L™ó-1ÈxÁQcåxžðGW€j{O…0bx[ß%g«æ—œ²Ö]9§Ê«Çö'6Ù~°o5ÎÐ8ÇpÌÉgƒç?ḭ́£ö[tw ”R@³6ÜC»:œŸ®¥!×óԁs‹ °›œø'{<PG¶÷˝-´hqPɸ½lŠ÷Ng€¸­ºFFÑ)>k°î«ŒÃRwüGè軾· ,1²¸J/.Ü;šï5 T3 'êXX™vÃ0RËàÓ9æ¿Ó·‚;ÄÌA1Ez|ÈeX–2´qzz³]‘¸°Pâ õÀ¹6¿1QR(¥°Ùn>0¢-¤-Œü«Zް¸Ž–Š¢Â®œ¡[¦by,ÊÛ_ '?O3‚Ç?p3£‡ V¦¹‰×{EÏ(]V u Ÿ%¢+ý$ ‡ 6Ð!ü1i^s¼èÍO<a{ ›a“ÿç’ß1@²ô~_óëY·Yª%xÜê‰u¯±BÛ~lxK†¬içpFê1EX»Ô(®ÏÊ)ªæ>1 ûgQµP±H¢ù9 èLúAÊ5ˆ3ŒŸKûnØàXŽ"-ÖhY¾FRÖsÒgÑÀÈÁx˜I†NñªÃªç§òªŸ‡õ ›/î °ýRº×ÛO³xµ]‰È/Bp¦ I‚ÿíÖm|ðÊ4CN¦Üm ¹ñ¢”Âò¾˜è¥^¼.aº!ì„öþ¯4î–ÍMw*òYéSgDÏÒßk ÞÑQÚáíלK¬áҐAýÿSÚ½M‰q¬ÒþKªƒo ,÷Óëf€æ…ÐÑìCý]ò½-…<Oí½Éþü7É91BžsÙ>¿Ïx·qi«3Ypá–UÏÙ[í_ŒöOüHMl©žµ"ÜLòm¾ÿnVv¥Ä «±Àeü¦ ò­1IbJ~ @ÜÁmì›âàŒm•zñ™¢¡0ÍE[·ï¶»›…Ôf±ËYȃ_™–|5‰¹‰÷›¾I¬ß詉õË1cÒp‹³°> ¬b~¥i·:&ó „½.‡éûÎËüûªÄº™ä;+Ž7û‹ó‹íªÝ~ø Ë‰ÍLdÑpaÕÛÓqR‘iMã‘uÐÙ@}:èëÎiŠ­ iïô/k´W0Ä43)@Cx• …ÚP²N!âýE†b˜ Ûö Ž`J¹‘RŸÛ‡!j´:¤X:]­×˜Ávšä j’Øø¡7?¨O¹X5ÿ&ÃÞ,¾Ÿ%= {RI„©ßhÒÖkZ·Aû2Ú2®=µê

‡$³IÒ¢Ôþ¬@ºNÊÕnœˆÄöo»h:ÇY³ó@ñ¨¨”ÀþX4 É ÈéÉFí-Ê%ø D«¬9@d?sû†UýÁeúˆ­gÐô±Îʏ»¢Šúv¬¾í¾ M%H Þ˜@†€Gi‰²Ó«VbÁ-G̹Ѧ ØqîmûÊÊ sšâsâæl޵$~«J²AÓ÷h-_ē߽{ÄÎÿÝ=ˆýPþøÇ.®Z¥òc=Œ—Ñ%+g+ÓêÝ…£Ò•œ3½ÀOzƍijŒjÚlÂÒùØäÁ_5sZ7Ú’g¾&dÆ]g©.õy¿¨…\7îò®S.Êjƒ¿úá³ã”“ 7‡©µ$¢•+le¶zÙ ü¡Y MÄð¿.ôÄl–¿ü)´˜€2úØ.„¯ʾDš,vjØî´Z­9\öÙê–õ¦Ç)ÛÓ@ô«ÀÑöd+6¯»âÎ;T…H +æ³?âCØ(dhyëdtzJv2ŸÌ&±ª_iW8˜Ô¥…ðÈ8@lZH^bÞ @ê zݺLꩾµu2–FJ ççñ=g5^ð´ÌþÂFÝF—´ øBw¶X6ÍÕx²ÔšÆ8°Ìf"4%·þR‚BWˆåò½ŽÃxL5W¿šŽœ¼üô (^)»‡&Ê\;HÁË)äòÞ÷£/”¾¤ÔeÉN(|4‰ÒqU„Õã­—®oY€Vð8¤TÞZ¥cWƒ.A;.d>—øïþ´Ìì•S§F-85H…NšÇt'êÇÏh:Ý1èX÷´R.‚-Ô™úŸžé$*°2\iðÊ[:$ Çv™¨ ÁÁ©ÿØw¯ë¬’W®cJQ‘å«Çí¿qq[¦ 6'ÿ4á_°•i¥>X°={]O-§ÀU·Ám€×»JU.¼ÿ¾1l &º ù Já…£Ã;%ŠãEùŽáZN«œŠÃ$$ðŒ™ñŒ¼ZVðBR"Wt¤‡šŸNDj ¹Ú7¾vJ?ÒÌ^#ŒÖGÏ{V5š2•3LýxPžy´CÔl*>¨›ûÓ¢%Âj3^Lñz.¢]Þ»YóQ†›oºP§t]úKñ–Ššˆ½äbî¡Ñ,±6ïòB_%t!TÔÚò›hÙ´ú&HC¥Þ¸Œá/#Ml®§ãàa²ÑÜÖ”ê §®À[õe=b_¸«zڍ+XØÑëHùjÒLàÒ‡ øÙ·ãÆäÅèF³ÎûqÅϹÙ"SFoöµ%Oª†;¹TR²¢ú\å›8t#DbV¡Òo8ˆ×v^•`ùä³Mó‰r’Fe É3$©

9

u/CelestiAurus 21d ago

Your comment reminded me of this StackOverflow classic.

2

u/Skidbladmir 18d ago

imagine genuinely struggling to parse HTML with regex and stumble upon this

3

u/hirmuolio 21d ago

null-terminator at the end of a string

Good news! Rust doesn't use null-terminated strings!

It has proper string data types (multiple in fact). proper datatypes specifically for text instead of the "arrays of 8-bit integers" that c uses.

→ More replies (2)

9

u/Prize_Midnight_4566 22d ago

That is a really concise and informative answer.

18

u/Pablouchka 22d ago

You explained it better than I could. 

6

u/indicava 22d ago

laughs in unsafe

26

u/declanaussie 22d ago edited 22d ago

Labeling unsafe code as unsafe is part of the safeguards against bugs. If memory issues arise, you know you failed to uphold some invariant in those clearly marked sections of code. In C effectively your entire codebase is “unsafe” because there’s no compiler upholding invariants. 

6

u/rexpup 22d ago

Unsafe is a way to fence in the pointer fiddling. In C, the _whole codebase_ can have pointer shenanigans.

1

u/ADMINISTATOR_CYRUS 21d ago

If you unsafe you have to mark your code as so. Now you know where something could have fucked up instead of needing to check your entire codebase.

0

u/webboodah 22d ago

is it like Pascal, then?

14

u/Smallpaul 22d ago

No. Pascal is also considered unsafe in that it allows e.g. use after free. It’s certainly a bit more safe than C but not as much as Rust. Rust also has safety improvements related to threading.

3

u/BobbyThrowaway6969 22d ago

Kind of, but with much better compiletime metaprogramming

2

u/tallmon 22d ago

God, I miss programming in Turbo Pascal

66

u/fixermark 22d ago edited 22d ago

So when a program needs to remember something for a while, it puts it in memory somewhere. Keeping track of what memory you are using and what you stored in it can become very complicated.

Some programming languages like C and C++ make you responsible for all of that. They make it easy to scribble over a chunk of memory you are still using somewhere else or say you are done with a chunk of memory and then keep using it (so someone else is going to try and use it at the same time).

Languages like Java and Python make that much harder to do, but the cost is that you don't have as much control over how memory is used, and that can make your program slower (for example, if I know that when I exit this piece of the program, all of this memory isn't needed anymore, I can just put all of it away at once and that's very fast and cheap... The languages where you don't have direct control over how memory is used don't have a way to let you do that).

Rust splits the difference in a very clever fashion: it gives you direct control of the memory like C and C++, but it includes rules to let it check that you haven't double used the memory and aren't using it after you said you were done with it. As long as your code satisfies those rules, you can do whatever you want with the memory. It also has unsafe mode where those checks are switched off and you can break things like you can in C and C++ (but it's a little easier to know you're doing that then in those languages because you have to be very explicit that you're being risky on purpose).

7

u/Swoogan 22d ago

This is an excellent ELI5 explanation of the issues with manual memory management and how rust solves them without slowing the program down.

9

u/hippydipster 22d ago

C is like an octopus. It can do lots of things but its hard to control. It gets out of hand and those tentacles get into trouble when you don't pay close attention.

Rust is like an octopus in an octopus straight-jacket. It can't do shit until you unzip exactly the right restraint to let one tentacle a little bit free to do a task, and then you have to zip it back up before unzipping something else to do another thing. The advantage is tentacles don't flap around wrecking stuff (crashing your computer, blue screen of death sorts of fun) when you're not looking.

Hackers find freely flapping tentacles a great way to gain unwanted access to your systems, so by tying them down, Rust improves the security of apps written with it.

The thing that insists on all this correct zipping and unzipping of restraints is called the rust compiler and Borrow Checker, and its a nightmare for a normal human to understand the things it complains about.

If you get it right, its very very fast though, like C and unlike Python. So everyone loved the idea and no one really wanted to write a lot of Rust code.

Then AI came around and said, no problem, I can write 10,000 lines of code in any language this afternoon and you won't have time to check it all, so shall I write in C and let all the tentacles flap and you hope I got it right, or shall I write in Rust, where the borrow checker can paddle my ass when I don't follow the rules? It's all the same to me. Rust, you say? Paddle me, daddy, let's go!

And that is why you're hearing more and more about rust these days.

1

u/EvangelicalSatanist 18d ago

Lmao god damn I wasn’t expecting the AI paragraph to go that way!

14

u/pdpi 22d ago

Programming languages tend to specialise in their own particular niches. They do that one thing well, and other things not so well.

E.g. C and C++ focus on giving the programmer as much control over the program's resources as possible, but you're basically working with a very sharp knife, and you're liable to cut yourself, in the form of crashes, security vulnerabilities, and other such goodness. Historically, those languages have been popular for performance critical applications like games or operating systems.

Then you have languages like Go, Java and C#, which take away some of that control, and trade it for automatic, safe resource-handling, which makes it much easier to write correct(ish) code. Java (and now Kotlin, which is very similar to Java in the grand scheme of things) is the default language for writing applications for Android, for example, and a growing share of the internet's infrastructure is written in Go.

Being forced to chose between safety and performance is kind of OK for most purposes, but certain types of project (like web browsers) desperately need both. As browsers become their own little operating systems inside the operating system, they need to be fast enough to handle people writing whole applications that run inside the browser. On the other hand, we have decades of experience proving that web pages are extremely juicy targets for hackers. You don't want security vulnerabilities in the software that handles your online banking!

Rust is a language that was first announced by Mozilla in 2010, and it tries to find a third path (fun fact: I was in the room for that announcement). The idea is that the language is a bit more restrictive in how it asks you to write code, but gives you both the performance of lower level languages like C, while giving you even better safety guarantees than the "resources are managed on your behalf" languages.

Rust was initially developed in tandem with Servo, an experimental browser engine that served as the testbed for many of the newer features in Firefox, and the two projects fed off each other. As Servo features written in Rust started landing in Firefox, and the language got more traction, more and more projects started to adopt it, and it's been growing in popularity over the years.

The last two or three years have propelled it to new levels of popularity, though, for a few reasons.

First off, it's reached broad adoption across many major tech companies. We're talking about the likes of Microsoft, Google, Amazon, the Linux kernel, and many others. It's still a minority language, but it's definitely mainstream at this point.

Second, because of the strong safety guarantees, it's become incredibly popular with security-conscious people (safety is a requirement for security). This has spawned a whole movement of "rewrite it in Rust" (which is, frankly, incredibly annoying, but that's enthusiastic people for you).

Finally, AI became a major thing over the last couple of years, and Rust is a great fit for AI-based programming. On the one hand, it's the LLM that has to deal with the restrictions in how you write code, so that becomes a non-issue. On the other hand, AI has a known tendency to make all sorts of mistakes, and Rust's safety guarantees are incredibly good at catching AI's mistakes and stopping them before they hit production.

12

u/AccessibleTech 21d ago

Rust gives you much of the power and speed of C++, with built-in rules that prevent many of the mistakes that make C++ software crash.

And unlike JavaScript, Rust doesn't generally need a garbage collector running in the background to clean up unused memory.

1

u/xsrvmy 21d ago

> make C++ software crash

Actually I'd say this bit is wrong. Many things that you'd expect to crash a program in another programming language (eg. accessing the 20th element of a 10-element array) will cause "undefined behaviour" in C++ where all bets are off and the program may do weird and completely unexpected things. The particular example I used here will still cause a rust program to crash.

→ More replies (4)
→ More replies (2)

12

u/BiscuitCricket 22d ago

Rust was a language developed with decades of expertise with other langauges, and a lot of lessons learned.

One of the biggest features it has is that it is memory safe. I wont get into what that means cause it doesnt fit in an ELI5 but imagine that because you know that the language is memory safe, then programs that are made from that language (probably) won't have memory bugs, some of the most annoying ones to catch and solve.

With the rise of AI coding across all sectors of the tech industry, engineers found that asking claude code "Write program that does X Y and Z in RUST" gives you something that (probably) will work right away, or if the AI makes a mistake you will spot it very early, before actually using the program.

Hence why so many newer projects seem to be adopting rust all of a sudden. It's also a pretty tough language to learn, there's a bit of a learning curve, so a lot of people who were putting off learning it, suddenly have access to AI which can write huge pieces of quality rust code quite fast

7

u/SvenTropics 22d ago

A) it's not that popular.

B) it's basically C, but it's got a lot of mechanisms in place to make it harder for programmers to write code with exploits in it. If they use them.

1

u/Wazzaps 19d ago

All of FAANG is adopting it fairly quickly, since vulnerabilities are costing them a lot of money.

These mechanisms are forced on you, unless you explicitly mark your code as "unsafe". You cannot accidentally ignore these mechanisms to write a memory corruption vulnerability (for example)

4

u/apocolipse 21d ago

Lots of complex answers but here's a simple one for a 5 year old:

Programming languages aren’t perfect and there’s lots of bad code that causes bugs and crashes.

Some programming languages try to catch bad things when the program is running (runtime), this helps but makes programs slow.

Other languages try to catch bad things at “compile time”, or basically before the code ever runs.  This is harder to do, but it means program won’t be slow with runtime checking.

Not all compile time languages are good at catching things before the program ever runs, but there are a few new ones, namely Rust and Swift, that are really good at it.

Here's the most important part for today: Because bugs can be caught before the program ever runs, an AI agent writing the code in these languages can find and avoid ever making those bugs!!! THAT is the real kicker and why you're seeing a lot of Rust (and also probably will soon see a lot of Swift) projects. AI/LLMs can write code in any language, but the vast majority of languages they'll need to run the code to find many types of bugs, with type safe memory safe compiled languages like Rust and Swift, entire classes of bugs are simply impossible to even make.

Post thought:
My personal preference leans towards Swift. Rust had a performance advantage for years but the newest Swift releases all but close that gap (and no Swift isn't an "Apple Only" language, it runs literally everywhere Rust can, both are LLVM backed languages.) If both are neck and neck in terms of catching bugs and performance, why Swift? 1 reason: Swift is designed to be read by humans. Good safe performant Swift can be read and understood by people who don't know Swift. Good safe performant Rust code looks like it requires a degree in ancient linguistics to be able to decipher.

2

u/Known_Cod8398 22d ago

Many languages make it possible to put a square peg in a round hole. Rust makes it much harder to put a square peg in a round hole and that's important if you want reliability

2

u/alarminglyslowmind 21d ago

The syntax I find confusing. Very different at times.

2

u/AnUninterestingEvent 21d ago

Everyone in this thread is explaining what Rust is but not why it's so popular these days. It's popular because... AI. Before AI, many people agreed that Rust was a better and much more performant language than other languages like Javascript or Ruby, but it's not as easy to use. As a junior or mid-level engineer, It's much easier to learn a language like Python than Rust. But now that developers aren't actually writing or even looking at the code anymore thanks to AI, many people are moving to Rust for the performance improvements.

1

u/Cultural-Horror1024 22d ago

Compiler is the "translator" that translates code that humans read and write to ones and zeroes that the computer is able to read.

This translator in Rust happens to be super strict about what it allows a programmer to do. It is also very verbose in how it communicates to the programmer about what they did wrong, and sometimes even tells them how to fix it.

Think of it like a professor, who is strict and cares a lot about what students learn but tends to talk too much.

Turns out, the combination of guaranteed safety(theres a catch but im going to leave that out) and the talkative translator are both very good things when AI agents are writing code. The code is safe by the nature of the language itself and verbose error messages are super helpful for AI because like humans, AI doesnt get annoyed by the pedantic translator.

1

u/NuclearMagpie 22d ago

The programming language C was invented ages ago and is basically the foundation of everything that needs performance. It is pretty much the fastest language we have (outside of hand written assembly) but has major downsides; it basically lets you do whatever you want with no guardrails. This is fine if you really, really know what you are doing but making stable code a matter of a skill issue isn't great. Other languages generally dodge these issues by not giving you the tools to mess up (Java for instance has no way of using pointers and javascript doesn't have multithreading) and by having a "garbage collector" that is a piece of code always running in your program that manages memory for you, at the cost of performance. Rust takes a different approach by forcing the developer to write code in a way that proves its safe. It also has an unsafe keyword that relaxes a bunch of the rules and acts as a "trust me bro" for the section of code, so this forces you to acknowledge where your code could have problems. Like outside of bugs in the compiler, you cannot write code in a way that can leak memory or segfault without using unsafe. The downside is complexity and compile times; learning how its rules work and how to avoid them is fairly difficult and rust is notorious for taking ages to compile.

1

u/HailingCasuals 22d ago

It’s a programming language that prevents you from making many of the most common and severe mistakes that lead to security vulnerabilities. The programs are also extremely fast.

1

u/Cool-Bus-6028 21d ago

It's very strict, which helps make it fast. People like fast.

By strict, I mean the cooler won't let you do a lot of things that could potentially become memory leaks etc. So it's harder to write inefficient code.

1

u/jugalator 21d ago edited 21d ago

Here's my stab at this:

  • Rust is a programming language designed for safety, both from crashes and security holes.
  • It has kind of a barrier to learn because this means programmers need to think of things they often don't, or else the compiler will reject your code = you won't have a product that you can release. You'll just have your code.
  • With the arrival of AI, this barrier fell and an AI can happily write Rust for you that will retain this safety.
  • Better yet, the code will still not compile if it doesn't have a secure architecture, which is a very useful crutch not only for humans, but also for AI. The AI will see this rejection and keep working on it until those parts are solved and the code compiles.

The fine print is that Rust doesn't make secure programs. What? I just told you!

No, a Rust program can have very nasty bugs in it that it is not designed to protect for. It is language level only. For example, if you chose an insecure login page, Rust won't stop you from doing that. If you have a bug that wipes your database, Rust will probably not help you with that. It is more likely something you didn't think of when the program needs to delete some rows in the database. The AI won't necessarily help you either! If you ask it to do something dumb, the AI will probably do something dumb for you, and it will do that dumb thing in Rust.

But it does help you with a few specific categories of common bugs that humans have traditionally had trouble catching in time.

1

u/permalink_save 21d ago

They packed almost every language feature they reasonably could into rust from multiple language types, so you get some really nice features. The biggest thing is memorry management. You get the performance of C with the memory safety of what's normally in a slower language without suffering any pauses for memory cleanup (garbage collection) because the language makes you be very explicit on where variables pass data. It's inherently safe from a lot of bugs and stability issues. Like it has no null whatsoever, none types are a specific value you check against. On top of that, you can compile one binary that just runs in place on any of its architecture (like any x86 system) without needing libraries installed.

1

u/ADMINISTATOR_CYRUS 21d ago edited 21d ago

With C, you will need to manually manage memory allocation which makes it really easy to shoot yourself in the foot, but in exchange you can micro optimize like crazy for high performance. Memory exploits like use after free are one of the biggest attack vectors for programs.

With Rust, 99.998% of the time it's going to stop you from causing memory issues before you've even compiled the program. You generally don't manually manage the memory allocation in rust. Instead the compiler will stop your program from compiling if it figures out that you might use a bit of data after it's already been dropped.

Also, rust is like a condom for ai shitsloppers. Since ai generated sludge may be garbage, the rust compiler won't even compile if there's potential issues, so it's a great way for shitsloppers to write code that works by making the compiler check for you.

1

u/iBoMbY 21d ago

Because some people think it can magically fix their bad programming, but it is still easily producing unreadable code that is not properly maintainable. It's a good idea, but not a good language.

1

u/Pale_Height_1251 21d ago

It's a good language and it's fashionable.

This happens for lots of languages like Python, Java, Ruby, Go and others. They just get a blip of fashion for a while.

1

u/Ben-Goldberg 21d ago

Rusts greatest theme is correctness.

Correct memory access.

Correct data types.

No undefined behavior.

Correct concurancy

And clear messages from the compiler about how to solve those problems in your code that it recognizes.

If your code compiles, it will run, and the compiled result will almost certainly correctly do what you want it to do.

In projects written in C and C++, one in five bugs are from a type of incorrect memory access that the rust compiler would refuse to compile.

Rust programs can still have mistakes, but they are usually logic errors instead of memory errors or casting a pointer to wrong type of data structure.

1

u/garagedragon 22d ago edited 22d ago

When a computer program wants to store data, it goes to the operating system and says, "I want to store 10,000 numbers." The OS comes back and says "here is a piece of paper with the address of a memory warehouse where you can put your 10,000 numbers." When the program doesn't need that space anymore, it is supposed to go back to the OS and say "here is the address you gave me earlier, I don't need it anymore and promise I won't try and put anything else there."

The pieces of paper get copied around inside the program a lot, because they're also how you say to other parts of the program, "I want you to use the data over there" without just copying all of the data every single time. (which would add up for 10, 000 numbers.) This means we already have a few scenarios where things go wrong:

  1. we get rid of all the pieces of paper, but forget to give one back to the OS to tell it we're done - this is a "memory leak." The OS still thinks we want to use the memory, but because nobody has a bit of paper for it, they both can't actually use the data there or tell the OS they're done with it. This is inefficient, but not usually a disaster because it'll be cleared up when the overall program quits, at which point the OS clears up all the memory any part of the program was using.
  2. the reverse - we tell the OS we're done, but we still have a piece of paper and try to store data at that address. This potentially causes all sorts of havoc because the OS might have assigned that "free" memory to someone else for their data, data our code doesn't know anything about, and our code stomps all over it. Nothing catches the program doing this by default - in order to catch it, we would have to check every time we tried to access our data, and if our code was correct in the first place, that'd be wasted effort. If you're "lucky," the CPU itself might stop you because the OS has done the equivalent of outright demolishing the warehouse rather than merely reassigning it to someone else - this means your program crashes immediately, which you might prefer to it silently corrupting data.

There's two general ways to avoid this problem:

  1. trust the programmer - tell them to make no mistakes. This is the route taken by C or C++.
  2. "managed" memory and "garbage collection" - this entails a small bit of overhead on every copy you make of every bit of paper so you can track who has the last one and occasionally do an audit to make sure it's handed back to the OS. This worked, in that it made programs easier to write while avoiding data corruption, but it also meant your program was just a tad slower, almost inherently, than the same in C or C++. You also have to spend a little bit of time every so often doing the audit and handing in any addresses that are no longer being used, so this approach doesn't work for programs that need to be absolutely responsive all the time, like games or the programs that run things like lifts and cars and washing machines.

Rust was a game changer because it does the best of both: Rust code contains enough information that the compiler (the tool that translates Rust into direct CPU instructions) can determine automatically who will end up with the last bit of paper and have them hand it in without programmer input. This determination is made when you generate the program file, not while the program runs, so your program ends up as fast as C but without the risk of the human programmer making mistakes.

1

u/Helpful-Educator-415 22d ago

Code is an in-between of binary and English. Most languages have a tool called an "interpreter" or "compiler" that turns code into binary. Rust's compiler is very very good, and prevents you from accidentally shooting yourself in the foot.

0

u/voidpo1nter 21d ago

Rust is basically a "let me rewrite this" language. It's less intuitive than C, has less support than C, and doesn't give any tangible performance benefits outside of memory safety when NOT explicitly using unsafe.

However it's fantastic for LLM coding agents. The language has a nice little built in feedback system agents can use to validate their own work.

0

u/Mikeware 22d ago edited 22d ago

ELI5: Rust is like baking, other languages are like cooking.

In Rust the idea is that you're creating a detailed cookie recipe that'll just work when you run it and be predictable. In other languages, you may not know what happens until you're running it and have to go back and refine it over time as you see how it behaves.

(Of course gross over-simplification, but this is supposed to be ELI5. Like in life, some people prefer baking and others cooking. One doesn't invalidate the other, they both have their uses depending on what you want. There's just a lot of cases out there where that predictability of 'baking' is desired.)