Latest / CyberCode Academy / Course 19 - Ultimate Rust Crash Course | Episode 4: Rust Foundations: Structs, Traits, Collections
Transcript
- 0:00Speaker 1: Okay, let's unpack this. If you've ever worked on a
- 0:02Speaker 1: large software project, you know the single biggest headache isn't
- 0:06Speaker 1: usually writing the code. No, it's making sure that code
- 0:10Speaker 1: is safe, predictable, and reliable over time.
- 0:13Speaker 2: Exactly.
- 0:14Speaker 1: Today we're doing a deep dive into an architectural philosophy
- 0:18Speaker 1: that really tackles those issues head on. It does it
- 0:22Speaker 1: by well ditching the complexity of traditional class hierarchies and
- 0:26Speaker 1: doubling down on explicit state management.
- 0:29Speaker 2: Exactly. We're moving beyond just describing data and behavior. We're
- 0:32Speaker 2: talking about actively enforcing correctness at the compiler level. So
- 0:37Speaker 2: our mission today is to dissect the four core conceptual
- 0:40Speaker 2: pillars that enable this robustness. We're talking strucks, traits, collections,
- 0:45Speaker 2: and enoms, Okay, we want to understand how they weave
- 0:48Speaker 2: together to create systems that frankly resist the common bugs
- 0:52Speaker 2: and vulnerabilities that plague other languages.
- 0:54Speaker 1: And I think we need to announce the foundational rule
- 0:56Speaker 1: right at the beginning, because it pretty much dictates everything
- 0:59Speaker 1: that follows. Data is instructs, and in this architecture there
- 1:03Speaker 1: is a hard, very deliberate choice to avoid class inheritance entirely.
- 1:08Speaker 2: That decision to separate data holding from behavior definition. It's
- 1:13Speaker 2: not just a technical detail, it's a philosophical shift. It's
- 1:16Speaker 2: all about composition over inheritance.
- 1:19Speaker 1: What does that mean in practice?
- 1:21Speaker 2: It forces us to be far more intentional about how
- 1:23Speaker 2: components interact, which is a massive win for long term
- 1:26Speaker 2: maintainability and system safety.
- 1:29Speaker 1: Okay, so let's start with the building block itself, structs.
- 1:33Speaker 1: For those familiar with object oriented languages, you can probably
- 1:36Speaker 1: think of a struct as a specialized form of a class, but.
- 1:39Speaker 2: Stripped down, Yes, stripped down to its essentials. It's a
- 1:42Speaker 2: custom container designed purely to group related data fields together.
- 1:46Speaker 1: So it's just a bucket for data pretty much.
- 1:48Speaker 2: Structs are the product of combining data types. You define
- 1:51Speaker 2: them using the keyword struct, you give it a name,
- 1:53Speaker 2: say red fox, and then you just list the fields inside.
- 1:56Speaker 1: But the syntax isn't the important part here, is it?
- 1:59Speaker 2: No? It's critical. Here is the contract. When you create
- 2:02Speaker 2: a new instance of a struct, you must initialize every
- 2:06Speaker 2: single field.
- 2:07Speaker 1: I see the architectural benefit instantly. That completely eliminates that
- 2:11Speaker 1: classic problem of creating an object where half the fields
- 2:16Speaker 1: are left uninitialized or default to.
- 2:18Speaker 2: Null, which is a huge source of bugs.
- 2:21Speaker 1: A notorious source of runtime errors and crashes. Yeah, but
- 2:25Speaker 1: uh it sounds a little verbose. If I have ten fields,
- 2:28Speaker 1: I need to manually specify every single time.
- 2:30Speaker 2: It can be absolutely That's why the convention is to
- 2:33Speaker 2: use what are called associated functions as constructors. These functions
- 2:37Speaker 2: are defined in an implement block, an implementation block that
- 2:40Speaker 2: is tied to the structure type itself, not a specific instance,
- 2:44Speaker 2: and by convention, we just call that function new.
- 2:47Speaker 1: So we define the complex initial logic inside RedFox dot new,
- 2:51Speaker 1: and then the consumer of the struct just calls that
- 2:53Speaker 1: function using the scope operator the double coling right. It
- 2:56Speaker 1: hides the complexity and ensures the instance is always created
- 2:59Speaker 1: in a valid, fully initialized state. That's a huge step
- 3:02Speaker 1: toward deterministic programming.
- 3:04Speaker 2: And this leads us to the distinction between an associated
- 3:06Speaker 2: function and a standard method. They both live inside that
- 3:09Speaker 2: impule block.
- 3:10Speaker 1: Okay, what's the difference.
- 3:11Speaker 2: Associated functions like new operate on the type itself. Methods, however,
- 3:16Speaker 2: always take some form of self that's the instance of
- 3:19Speaker 2: the struct as their first argument.
- 3:22Speaker 1: Meaning they operate on the data held within that specific red.
- 3:25Speaker 2: Fox exactly and accessing fields or calling methods once you
- 3:28Speaker 2: have an instance just uses simple dot syntax.
- 3:31Speaker 1: So to reiterate the foundational rule here, structs are simple
- 3:35Speaker 1: data bundles. They hold the data, They can describe methods
- 3:39Speaker 1: that act on that data, but they cannot inherit structure
- 3:42Speaker 1: or behavior from another structure.
- 3:43Speaker 2: That's the rule.
- 3:44Speaker 1: So what is the deep architectural reason for this rejection
- 3:48Speaker 1: of inheritance.
- 3:49Speaker 2: Well, inheritance, while it can be powerful, it tightly couples
- 3:52Speaker 2: structures together and that makes the system brittle. Programmers often
- 3:56Speaker 2: call it the fragile base class.
- 3:58Speaker 1: Problem right where you change a parent class and it
- 4:00Speaker 1: unexpectedly breaks a bunch of unrelated child classes.
- 4:02Speaker 2: You got it, So by removing it, the architecture forces decoupling.
- 4:07Speaker 2: It ensures that if struct A needs functionality from struct B,
- 4:10Speaker 2: it doesn't get it by becoming a B.
- 4:12Speaker 1: So how does it get it?
- 4:13Speaker 2: It gets it through an independent, definable contract. And those
- 4:17Speaker 2: contracts are traits.
- 4:19Speaker 1: Okay, So here is where the concept of composition truly
- 4:22Speaker 1: comes into its own. Traits are the definition of required behavior.
- 4:27Speaker 1: They're like interfaces in other languages, setting a standard for
- 4:30Speaker 1: functions or methods that a type must implement to qualify
- 4:34Speaker 1: for that trait.
- 4:35Speaker 2: Yes, exactly. If we define a trait called noisy, for example,
- 4:38Speaker 2: and it requires a method called get noise, then any
- 4:41Speaker 2: struct whether it's a red Fox, a washing machine, or
- 4:44Speaker 2: space probe, can implement.
- 4:46Speaker 1: That trait, and the implementation syntax is simple, implement noisy
- 4:49Speaker 1: for red Fox.
- 4:50Speaker 2: That's it.
- 4:51Speaker 1: Now. If I'm coming from a class based background, I'd
- 4:53Speaker 1: ask why not just define get noise directly on the
- 4:55Speaker 1: red Fox struct Why introduce this extra layer of the trait.
- 4:59Speaker 2: Because that extra layer is the gateway to generics and
- 5:02Speaker 2: true abstraction.
- 5:03Speaker 1: Okay, explain that.
- 5:04Speaker 2: Without traits, if you wrote a function that took a
- 5:07Speaker 2: red Fox and printed its noise, you'd need to write
- 5:10Speaker 2: a whole separate function for a washing machine. But with traits,
- 5:13Speaker 2: you write one generic function that says I accept any
- 5:16Speaker 2: type provided that type implements the noisy trait, So.
- 5:19Speaker 1: You don't care what the type is, only what it
- 5:22Speaker 1: can do exactly.
- 5:23Speaker 2: That's the core idea that.
- 5:24Speaker 1: Opens up incredible possibilities for building usable library code that
- 5:29Speaker 1: operates independently of the concrete data structures. It's the difference
- 5:33Speaker 1: between hard coding solutions and designing flexible.
- 5:36Speaker 2: Systems, and the flexibility extends to implementation too, so you
- 5:40Speaker 2: can implement any trait for any struct or type, provided
- 5:44Speaker 2: either the trait or the struct is defined in your
- 5:46Speaker 2: current project. This ability, known as the orphan rule, is
- 5:50Speaker 2: crucial for extensibility.
- 5:52Speaker 1: So you could implement a third party library's trait on
- 5:55Speaker 1: your own customs.
- 5:56Speaker 2: Struct or conversely, implement your custom trait on a built
- 5:59Speaker 2: in time like making an integer type noisy.
- 6:02Speaker 1: That's really flexible. Let's look at a critical built in
- 6:05Speaker 1: example of a trait that speaks directly to these architectural
- 6:08Speaker 1: trade offs, the copy trait.
- 6:10Speaker 2: Right. The copy trait relates directly to memory semantics. When
- 6:14Speaker 2: you assign or passive value in this system, it typically
- 6:17Speaker 2: follows semantics ownership moves and the old variable becomes invalid.
- 6:21Speaker 1: But for small primitive types like integers, floats, or Boolean's
- 6:26Speaker 1: data that fits neatly on the stack, we want that
- 6:29Speaker 1: assignment to just be a cheap quick copy exactly.
- 6:31Speaker 2: So if a type implements the copy trait, the compiler
- 6:34Speaker 2: knows it's safe and efficient to just duplicate the bit
- 6:37Speaker 2: pattern rather than transferring ownership.
- 6:39Speaker 1: But there's a crucial limitation, well.
- 6:41Speaker 2: A very important one. If a type involves a pointer
- 6:44Speaker 2: to data stored on the heap, like a dynamic list
- 6:47Speaker 2: or a string. It cannot implement copy.
- 6:50Speaker 1: Because a simple bit level duplication would lead to two
- 6:53Speaker 1: instances owning the same memory address.
- 6:56Speaker 2: Which spells disaster, double free errors, memory corruption, all, all
- 7:00Speaker 2: of it. So it's a mechanism that forces you to
- 7:02Speaker 2: be explicit about your memory management. It prevents a whole
- 7:05Speaker 2: class of bugs.
- 7:06Speaker 1: This composition philosophy is best illustrated by how it solves
- 7:10Speaker 1: the traditional inheritance mess. Take the classic gaming scenario. We
- 7:14Speaker 1: have a goose, a pegasus, and a horse.
- 7:16Speaker 2: Right, So let's say the goose and the pegasus can
- 7:19Speaker 2: both implement the fly trait. Okay, and the pegasus and
- 7:22Speaker 2: the horse can both implement the ride trait, and.
- 7:25Speaker 1: Perhaps humorously, the goose and the horse can implement and
- 7:27Speaker 1: explode trae.
- 7:28Speaker 2: Sure why not?
- 7:30Speaker 1: Now? If we try to model that using object inheritance,
- 7:33Speaker 1: we'd immediately run into the diamond problem or need these
- 7:36Speaker 1: complex abstract based classes that only partially implement methods.
- 7:40Speaker 2: It becomes a total tangle of is a relationships that
- 7:43Speaker 2: don't quite fit.
- 7:45Speaker 1: But with traits, it's elegant.
- 7:47Speaker 2: It's clean. Goose implements fly and implements explode, Pegasus implements
- 7:53Speaker 2: fly and implements ride. The behavior is composed from these discrete,
- 7:57Speaker 2: focused contracts.
- 7:58Speaker 1: This also dramatically proves unit testing because you can easily
- 8:02Speaker 1: mock or test just the fly behavior without needing to
- 8:06Speaker 1: instantiate the entire complex object hierarchy. Absolutely, and trades themselves
- 8:10Speaker 1: can form hierarchies too.
- 8:11Speaker 2: Right they can. If you define a run trait that
- 8:14Speaker 2: inherits from a movement trait, well, implementing run automatically forces
- 8:18Speaker 2: your struct to implement all the methods required by movement.
- 8:21Speaker 1: As well, so it's behavioral dependency management, not structural inheritance precisely.
- 8:26Speaker 2: Furthermore, traits can provide default behavior. You can define a
- 8:29Speaker 2: method inside the trait with a default implementation body, and.
- 8:33Speaker 1: If a struct implements that trade but doesn't override the method,
- 8:37Speaker 1: it just gets the default.
- 8:38Speaker 2: Behavior, but it can override it if it needs custom behavior.
- 8:42Speaker 2: It gives you a sliding scale of customization.
- 8:44Speaker 1: A quick technical detail we should mention traits can't define
- 8:48Speaker 1: data fields.
- 8:49Speaker 2: No, they are pure contracts for behavior.
- 8:51Speaker 1: So if you need a trade to access state, the
- 8:54Speaker 1: architectural compromise is defining getter and setter methods within the
- 8:58Speaker 1: trade instead right.
- 9:00Speaker 2: This is how state management is enforced. Like in the
- 9:02Speaker 2: byte exercise for the grapes struct the trait requires a
- 9:06Speaker 2: method that takes a mutable reference to self, which is
- 9:09Speaker 2: a mut.
- 9:10Speaker 1: Self, forcing the implementation to explicitly handle that state. Changelike
- 9:15Speaker 1: updating the amount left field.
- 9:17Speaker 2: You've got it.
- 9:17Speaker 1: So we've established how to define reliable single data points
- 9:20Speaker 1: and their required behaviors. Now we shift to managing large
- 9:23Speaker 1: groups of that data, which brings us to.
- 9:25Speaker 2: Collections and the primary workhorse here is the vector.
- 9:28Speaker 1: Or a vec, which is essentially a list or dynamic array,
- 9:32Speaker 1: but critically it holds objects of a single specified type.
- 9:36Speaker 2: And those items are stored contiguously in memory. That contiguous
- 9:40Speaker 2: layout is key to its performance. It makes indexing and
- 9:44Speaker 2: iterating extremely fast.
- 9:46Speaker 1: Functionally, it acts like a stack right yep, push ads
- 9:48Speaker 1: to the end and pop moves from the end YEP.
- 9:51Speaker 2: But this is where we really see that safety first
- 9:53Speaker 2: philosophy applied to data access.
- 9:56Speaker 1: You talk about bounds checking. I AM.
- 9:58Speaker 2: If you try to access an index that is outside
- 10:01Speaker 2: the bounds of the vector, the program doesn't just retrieve
- 10:03Speaker 2: garbage data or allow a buffer overflow.
- 10:06Speaker 1: No, it will intentionally panic. It crashes the program.
- 10:10Speaker 2: And that seems harsh to a new learner, but architecturally
- 10:13Speaker 2: it's a feature. The system refuses to allow silent memory corruption.
- 10:17Speaker 1: It trades potential data insecurity for a guaranteed explicit failure.
- 10:22Speaker 2: Forcing the developer to address the bounds check before deployment.
- 10:25Speaker 1: You can contrast that with other collections like the link list.
- 10:28Speaker 1: A link list allows for lightning fast insertion and removal
- 10:31Speaker 1: anywhere in the.
- 10:31Speaker 2: Sequence, but because the items are scattered across the heap,
- 10:34Speaker 2: iteration and indexing are much much slower than a contiguous VEC.
- 10:38Speaker 1: So the architectural choice depends entirely on your priority fast
- 10:42Speaker 1: iteration or fast arbitrary modification.
- 10:45Speaker 2: And when we need rapid lookups based on a key,
- 10:48Speaker 2: we use the hashmap.
- 10:49Speaker 1: Right like a dictionary. It's generic, requires a key type
- 10:52Speaker 1: and a value type, and it guarantees that lookups, insertions,
- 10:55Speaker 1: and removals happen in constant.
- 10:57Speaker 2: Time or oh one, yeah now.
- 10:59Speaker 1: Hash maps vent a crucial transition point. When you try
- 11:02Speaker 1: to retrieve an item using a key, that key might
- 11:06Speaker 1: not exist. If you use the removed method, you might
- 11:08Speaker 1: get something back, or you might not, so How does
- 11:11Speaker 1: the system handle this inherent uncertainty without falling back on
- 11:15Speaker 1: dangerous concepts.
- 11:16Speaker 2: Like null It uses enoms, and this is where the
- 11:18Speaker 2: architecture truly pulls away from traditional languages. Enoms here aren't
- 11:22Speaker 2: just lists of named constants.
- 11:24Speaker 1: No, they're much more.
- 11:25Speaker 2: They are what are known in computer science as algebraic
- 11:28Speaker 2: data types.
- 11:29Speaker 1: Okay, algebraic data types sounds like textbook jargon. Can you
- 11:33Speaker 1: explain that simply?
- 11:34Speaker 2: Certainly? In programming, we have product types like structs, where
- 11:38Speaker 2: the value is the combination of all its fields.
- 11:40Speaker 1: So as struct with two fields has a value space
- 11:44Speaker 1: that's the product of the possibilities of those two fields.
- 11:46Speaker 2: Correct Enoms, however, are some types. A single enom value
- 11:50Speaker 2: can be variant A, or variant B or variant C.
- 11:55Speaker 2: The value is the sum of the possibilities.
- 11:57Speaker 1: Which makes enoms perfect for modeling distinct, exhaustive states.
- 12:01Speaker 2: And that structural ability to define a state that is
- 12:04Speaker 2: one of many makes them unbelievably powerful, especially since each
- 12:08Speaker 2: variant can carry its own distinct set of associated data
- 12:12Speaker 2: a simple type, a tupole, or even an anonymous struct wow.
- 12:16Speaker 2: And the standard library leverages this power in two pervasive ways. First,
- 12:20Speaker 2: the generic option t enom.
- 12:22Speaker 1: This is the safe explicit alternative to null. A value
- 12:25Speaker 1: is either present wrapped in the sum t variant, or
- 12:28Speaker 1: it is explicitly absent, represented by the.
- 12:30Speaker 2: Non variant no more null point or exception.
- 12:33Speaker 1: And second the result t enom.
- 12:34Speaker 2: This is the standard for any operation that might fail.
- 12:37Speaker 2: It clearly separates the success pathway OKT, which contains the
- 12:41Speaker 2: useful result.
- 12:41Speaker 1: From the failure pathway ear, which contains the specific error information.
- 12:45Speaker 2: And the philosophy here is enforced by the compiler. Result
- 12:49Speaker 2: often comes with a must use annotation.
- 12:52Speaker 1: So if you call a function that returns a result
- 12:54Speaker 1: and you don't do anything with.
- 12:55Speaker 2: It, the compiler issues a warning. It's actively telling you
- 12:59Speaker 2: the developer, you are ignoring a potential failure state and
- 13:03Speaker 2: that is unsafe.
- 13:04Speaker 1: This shifts the cognitive load from debugging unexpected runtime errors
- 13:08Speaker 1: to making explicit compile time decisions. You are forced to
- 13:12Speaker 1: deal with the failure before the code even runs. Now,
- 13:15Speaker 1: if you're being lazy, you can use methyls like unwrap or.
- 13:18Speaker 2: Expect, which effectively tell the program, I swear this will
- 13:21Speaker 2: always succeed, and if you're wrong.
- 13:23Speaker 1: The program crashes with a detailed message not ideal for production.
- 13:27Speaker 2: No, So for robust systems, we need a clean, safe
- 13:31Speaker 2: way to examine which variant an enom is holding and
- 13:34Speaker 2: extract the data inside. And that's where pattern matching comes in.
- 13:37Speaker 1: Since an enom can contain these nested data structures, we
- 13:40Speaker 1: need sophisticated tools to extract that data. The simplest tool
- 13:44Speaker 1: is the if let expression.
- 13:46Speaker 2: Right. This is useful when you only care about one
- 13:48Speaker 2: specific variant. If the variable matches the pattern you specified,
- 13:52Speaker 2: the code block runs and any extracted data is available
- 13:55Speaker 2: inside that block.
- 13:57Speaker 1: But when you're dealing with result or any complex date machine,
- 14:01Speaker 1: you have to use the match expression.
- 14:02Speaker 2: This is the core control flow mechanism for safety. Because
- 14:06Speaker 2: it requires exhaustive patterns, you must account for every single
- 14:10Speaker 2: possible variant the enom could hold.
- 14:12Speaker 1: The match expression uses the fat arrow to connect a
- 14:15Speaker 1: pattern to its execution branche. And if you have variants
- 14:18Speaker 1: you simply don't care about.
- 14:20Speaker 2: A catchell, you use the single underscore as the wildcard pattern.
- 14:25Speaker 2: The Sayshi check here is profound. If you define an
- 14:28Speaker 2: enom with three states and you only write two match arms,
- 14:31Speaker 2: the compiler refuses to compile.
- 14:33Speaker 1: It forces you to cover that faces.
- 14:35Speaker 2: You Let's use the practical example of shot classification. Imagine
- 14:39Speaker 2: a shot enom with three variants bullseye hit f sixty
- 14:42Speaker 2: four which holds the distance, and miss. Okay, we can
- 14:44Speaker 2: define a method on that shot enom that calculates points
- 14:47Speaker 2: based on the result.
- 14:48Speaker 1: So we'd use a match expression on the instance of
- 14:50Speaker 1: the shot. The arms would explicitly match shot bullseye returning
- 14:55Speaker 1: five points and shot miss returning zero.
- 14:58Speaker 2: Simple enough, But for the shot hit distance variant, we
- 15:01Speaker 2: can introduce more complexity. We can use what are called
- 15:04Speaker 2: guards within the match arms.
- 15:06Speaker 1: Okay, what's a guard?
- 15:07Speaker 2: We might match shot that hicks, but add an if
- 15:09Speaker 2: by three point zero guard to assigned two points. If
- 15:12Speaker 2: that guard fails, the match moves to the next.
- 15:14Speaker 1: Arm, which could be another shot hit pattern without the guard,
- 15:17Speaker 1: or maybe a final wildcard to assign one point for
- 15:20Speaker 1: any other general hit.
- 15:22Speaker 2: Exactly. It lets us handle range based logic while staying
- 15:25Speaker 2: strictly within the exhaustive safety structure of the match.
- 15:28Speaker 1: It's an incredibly powerful way to map highly nuanced business
- 15:32Speaker 1: logic onto simple, verifiable data structures.
- 15:36Speaker 2: Precisely, we've defined an architectural stack that mandates intentionality structs
- 15:41Speaker 2: define the data traits define the shared behavior through composition,
- 15:45Speaker 2: and the enoms specifically option and result, combined with pattern matching,
- 15:49Speaker 2: enforce safe, explicit handling of every potential outcome.
- 15:52Speaker 1: This whole system is designed to push mistakes from runtime,
- 15:56Speaker 1: where they crash the user's application.
- 15:58Speaker 2: Back to compile time, where the compiles seiler forces you
- 16:01Speaker 2: to fix the logic.
- 16:02Speaker 1: It creates predictable, robust code by requiring exhaustive error handling
- 16:07Speaker 1: and avoiding the implicit complexity of inheritance.
- 16:10Speaker 2: So, as a final provocation for you to think about,
- 16:12Speaker 2: consider that intentionality. If you are designing a simple function
- 16:16Speaker 2: to save a user's data to a disk, and that
- 16:18Speaker 2: function returned to result, what three common io failure scenarios
- 16:23Speaker 2: should your function explicitly report back to the user using
- 16:27Speaker 2: that error variant?
- 16:28Speaker 1: And maybe more importantly, how would you structure the match
- 16:31Speaker 1: expression that consumes that function's result to ensure that for
- 16:34Speaker 1: each of those three explicit errors maybe file not found,
- 16:37Speaker 1: permission denied, or disfol you provide a tailored, user friendly
- 16:41Speaker 1: response rather than just letting the program crash. That kind
- 16:44Speaker 1: of exhaustive planning is the true power of this architecture.