Crust of Rust: Dispatch, Monomorphization and Fat Pointers — Jon Gjengset
Jon Gjengset dives into static and dynamic dispatch in Rust, covering generics, monomorphization, vtables, trait objects, auto traits and the Sized bound.
Search this transcript in the workbenchRead the transcript
Transcript source: creator-uploaded captions on YouTube, unedited. Paragraph breaks and timestamps added by Vidleaf.
[0:07] Hello folks, welcome back to yet another Crust of Rust. This one, I'm hoping I didn't bite off too much to cover in like an hour and a half to two hours. I guess by the time you watch this recording afterwards, you'll see whether I succeeded or not. So for this one, what I wanted to cover was... a sort of chunk of semi-related topics around traits and dynamic and static dispatch, the size trait, like wide or fat pointers.
[0:44] And some of the things around like V tables, coherence, they all have this kind of dynamic and static approach to them. They're all sort of tied together, some more so than others. And I get a lot of questions about each one. And I figured I should just do one stream where we talk through how all of this stuff works and how it fits together. I'm hoping that we don't... end up too far down any one rat hole. I think what I'll try to do is cover most of it in sort of workable detail.
[1:18] And then we might do sort of a deep dive on one of them in some later stream. But in order to try to contain it to the time, you might find that I skip over some of the detail, and hopefully that'll be OK. So I actually wanted to start this time on The Rust Book. So The Rust Book has a chapter on generic types and traits and lifetimes. And there's this one subsection in there on the performance of code using generics. And this is a section that, if you've read the book, and I highly recommend you do if you haven't already, might have struck you as, you might have read it and be like, that sounds like magic.
[1:59] And in some sense, what this stream is about is trying to deconstruct that magic and figure out what's inside. And in particular, it talks about this idea of monomorphization. And monomorphization is the, as the text says, the process of turning generic code into specific code by filling in the concrete types that are used when compiled. But that's sort of abstract. So let's try to pick up a slightly more concrete example and then work from there. Let's go with new lib.
[2:34] We're going to call this one. Hmm, naming is hard. It doesn't matter, but that makes it even harder because there are no constraints. We're gonna go with example written in Norwegian. All right, let's get rid of this test.
[3:06] We don't need no test. So let's say that you have a function greater. It is generic over T. Actually, let's go even simpler. Let's say that we're going to have a function strlen. And it's going to take anything that implements ASRF str. And it's going to give you back a use size. So we're going to do as ref len.
[3:39] Real simple function here. Let me make it a little bit larger. So this is a generic function. You could just as well have written it as s is s to use size where s implements s ref stir. These two are equivalent. s ref len. And I guess we'll make these pub to make the compiler stop complaining.
[4:12] So these two are equivalent. They're not quite equivalent, but they do the same thing. And both of them are generic functions. They can take in any type that can be turned into a reference to a star, which is what this says and same as what this trait bound does. And what happens is if we write any function, let's say foo, and it calls strlen of, let's say, hello world. And then it also calls strlen of string from hello world.
[4:53] in Norwegian. That is a good, handy shortcut for picking examples. So just to see why these are different, this is giving in a type of a static str. This is giving in the type of string. Whoa. Right? So this is where we get into the point of this function is generic. It doesn't just accept a string reference.
[5:25] It accepts any type that can be turned into a string reference. So string, for example, implements as ref str. Because if you have a reference to a string, you can trivially get a reference to a str. Because the internal representation of a string is a str. Right? So here we immediately see sort of why generics are useful. It's because it enables you to call into a given function in a more flexible or ergonomic manner. And behind the scenes, what happens, and this is what the Rust book is talking about when it talks about monomorphization, is that the compiler actually generates two copies of this function.
[6:08] one for each of these types. So at compile time, what we're actually going to end up with is like a sterling ref stir, which actually takes a stir and calls a stud Len. And we're going to end up and we're going to end up with a sterling string, which takes a string and does the same thing. So this one generic definition gets turned by the compiler into these multiple non-generic implementations.
[6:48] That's the process of monomorphization. And this is sort of key to how generics work in Rust. And this process doesn't just happen for functions, they happen for types too. So imagine that you have a hash map that's generic over the key and the value. You actually get a full copy of the entire struct and all of its methods, one for each type that it is used by. Notice that it doesn't generate... copies of this for types that we didn't invoke it with.
[7:18] This is not like a generate for every possible type. It is generate for any type sort of on demand, but on demand determined at compile time. If you see code that needs this function for a given type, then generate it at that point in time. And a type would be the same. Like a hash map would only, a particular instance of the hash map type would only be generated if that type combination actually appeared somewhere in the code. This is actually also one of the reasons why it's a little bit hard to make Rust, to compile Rust code and then ship people a binary that they can use as a library.
[7:58] Because imagine that if you had this in your Rust library that you wanted to sort of distribute in binary form, think like dynamically linked libraries and stuff, it's actually fairly complicated because The contract is that Rust is supposed to generate distinct copies of this function for each type, but it might be instantiated with a type in a consumer that isn't defined where the source function is defined in the originating library. And therefore, you need the source in order to generate all those instances.
[8:31] And the reason why monomorphization is great is because you end up producing potentially much more efficient code, right? Sterling is a bit of a bad example here, but let's imagine that we had something a little more complex. Actually, a good example is HashMap. I'm not going to write out the full definition of a HashMap here. But what you end up with HashMap is because you get a copy of the type for each concrete type you use. Imagine that one instance of the HashMap has the key be a...
[9:06] a string and another instance has the key be a number, you would actually end up with the compiler, when it generates the code for each of the methods of the HashMap, it would generate, like it would sort of inline the definition of say the hashing function for each key type. So the one, the HashMap version of the code that uses string would sort of put in the code for hashing a string directly into the HashMap code, and it could optimize that code based on the fact that that type is a string.
[9:40] Similarly, for something like a number, it might be able to skip hashing altogether because it realizes, once it sort of monomorphizes all the generics, that actually the hash is just the value of the number. That might not actually be true, but you get the sense of, like, the compiler gets to see the concrete written-out code for the particular types that are used. which lets it optimize a lot better. Does this all make sense before we move on to the more complicated aspects of this? Does the general idea of generics and why monomotivation is nice make sense?
[10:28] So the downside, as someone observed in chat, is, yeah, for monomorphization, one of the downsides is that your binary ends up being larger because you need to generate a copy of the type or the function for every type that it's used with. It's not quite as bad as like just multiply by the number of types. One of the reasons is because for HashMap, for example, you might only use a subset of the methods for any given type combination. And it won't generate like... Like if you ever have a HashMap that has string as the key type, it generates the entire HashMap, like all of the methods for HashMap for the string key type.
[11:08] It will only generate the methods you actually end up calling. So that amortizes the cost a little bit. But it is true that it leads to more code in the final binary. And a sort of side effect of that is that your code can be a little less efficient in the sense that now, rather than having one function called Sterlin, that like one sequence of like assembly, like machine code, really, that the computer can jump to.
[11:40] And then it can keep those lines of machine code like in cache, which lets it execute it more, more efficiently the next time around, what you end up with instead is you have two. different functions, and some code jumps to one and some code jumps to the other, and they have to be cached separately because they're separate regions of memory, as you actually end up with a slightly worse cache efficiency for your instruction cache, which is a downside. It's also a little bit expensive in the sense that the compiler does need to generate these copies, but usually that's not too much of a cost, like actually generating these, unless you end up instantiating with a very large number of types.
[12:22] Um, Is that one of the primary reasons Rust binaries are larger than C ones? So that is slightly different. Rust binaries statically compile more stuff, which might be part of the reason. Part of it is monomorphization. Part of it is, I forget the exact details, but I think there's more stuff from the standard library that gets compiled in. And another really big one is that Rust often builds in debug symbols.
[12:54] which if you don't strip them from the binary, you end up with a binary that has very little actual machine code, but a lot of debug symbols, as you might want to try to just strip the binary. Will the compiler try to inline generated functions? Yeah, so this is one of the reasons why monomorphization is really good, is because it doesn't just inline whether it's string or str, but if you have, say, a PubFn, like... a bool then, which takes a Boolean, and it takes an f, which is a function, and it returns you an option t.
[13:42] And then let's say the implementation is something like, if b, then some f else. And this function actually just landed in the standard library, although as a method on bool. So here, if you ever ran this function with a particularly provided... closure or function, it would actually generate a copy of bool then with the code for the closure you passed in directly inline into this function. And so it could be optimized accordingly.
[14:14] So yeah, it does end up inlining. Inlining is the wrong word here. It has the option of inlining and optimizing as based on that. It doesn't have to. It's just that because it gets monomorphized to the particular type, it knows exactly what that type is, and it can choose to inline if it wishes, which is an important distinction. Big reason for larger size is standard lib.
[14:44] That's not quite true because only the parts of the standard library that you actually use end up getting put into your binary. It is true, though, that if you're using a lot of generics from the standard library, that ends up growing the size. How big of a cost is duplication of methods? Basically none. I think the actual generation of multiple functions isn't that important, but what is important is if you generate many copies of a function, you have to compile each of them into machine code, which slows down the compilation process. Wouldn't strlen string take ref string rather than just string by value?
[15:23] It could take either, actually. They will both work, which is one of the reasons why taking askRefStir is nice. How do dynamic libraries handle generics? They don't. This is one of the reasons why it's challenging to do dynamic linking of Rust libraries, or even just distributing Rust libraries in binary form. And it's something that I think in Swift, they've been trying to stabilize something like this.
[15:54] We don't quite know how to use it for Rust yet. And yeah, you can't use it for something like if you want a C dilib, like a dynamically linked library in Rust that has a bunch of like external functions, those can't be generic. All right. So now that we have an idea of what monomorphization is, I want to talk a little bit about what the actual process of dispatch here.
[16:27] So dispatch is the idea of... Actually, let me give you a slightly better example that we can work with for a little bit longer throughout the stream. So let's define our own trait. We're going to call this trait... just call it Hello, it's simple enough, or I guess let's go with the Norwegian hi. And it just has one method.
[17:00] And let's say it actually returns nothing, it just has a symbol as a single function that just lets you say hello in Norwegian. And we can imagine that we implement that trait for let's say, stir. Um, and all that's going to do is it's going to print line, uh, self oops. Um, and then we're going to do, uh, I guess let's just go with J dot.
[17:40] Hi. Ah, can't type today. So what happens behind the scenes here is that when the compiler tries to generate the code for this, it determines the type of this, then it looks at which methods are available on just the str reference type. It doesn't find one called high. And then it looks at the traits that are in scope, it finds that there is a high method on this, which is implemented for the receiver type.
[18:18] And so it ends up calling that. Seems fine. Now let's imagine that we have a sort of generic version of this, where we take something that implements high, and I guess h. And it's just going to call h.high. So this one's trickier, right? When the compiler has to generate the machine code for this, it needs to somehow call this method, but it doesn't actually know the type of H. And this is where monomorphization comes into play, right?
[18:51] That in reality, what's gonna end up being generated is a bar str, which has H, B, str. And now, dispatching this, figuring out what to call here is trivial, because we know the concrete type. So this is what's known as static dispatch. That is, at compile time, the compiler knows what the actual type is. And therefore, when it tries to call this method, it just knows that that is this method.
[19:22] And it can just jump to, like this basically becomes a call in like assembly code to call this function, which is at some known location in memory, right? Because it's just where this method is. Does that make sense for static dispatch? That actually figuring out how to compile this code becomes trivial once you can generate this method, because this method is really the same as this. And these are both trivial to figure out where the high method lives.
[20:05] So now that we've looked at this sort of static dispatch, you might wonder, well, what is the alternative? What if we don't want to generate a bunch of different copies for this? So this is where we go back to dynamically sized types. Oh, sorry, yeah, impel-hi here is just syntactic sugar for generics. This is equivalent, like I showed with Sterling before, this is is equivalent to H is high.
[20:40] These two are equivalent. Yeah, so what then is the alternative? We don't want this monomorphization, we don't want multiple copies. Or the other reason why you might imagine this is, let's say that you want to let's say you have a vector of things that implement high. In foo here, I want to have a vector of this.
[21:21] And I want to do like for h in this vector, call h.high. That's fine if they're all the same type. But what if I wanted a sort of collection or sequence or set in some way of things that are high, but I don't need them to actually be the same type. All I care about is that they implement this trait. So more concretely, imagine that I want to write bar, and I want to take anything that is a, say, slice, of like, imple high.
[22:02] Let's start start with this version, right. So for H in s, h dot high. This works fine. I can call bar with say a with something like this. works just fine, that compiles just fine. Similarly, I can do I can turn each of them into strings. That also works just fine.
[22:40] Oh, right, I didn't implement this for string. So that works just fine. But let's imagine that I want to be able to call it with like, this should really be fine. But I can't do that, right? Like, I can't create a vector of things that are different types. That's not a thing that I can make in the first place. What I really, but in this case, I don't actually care what the concrete type is.
[23:11] I don't care that these are strings. All I care about is the fact that I want them to implement the height trait. That's all that matters to me. So I should be able to create a vector of things that have this behavior without caring about the concrete type. And this is where we get into the area of dynamic dispatch and trait objects. And the book has a chapter on this too. Let me find where that one is. I've opened it in the wrong order, which was silly of me.
[23:50] Sorry about the jumping around. It is down here in the chapter here. So the book has a pretty decent chapter where it talks about the ability to treat things that are different concrete types as the same type. So another example that they use is in the case of like a GUI, you might have lots of things that are drawable, like they implement the draw trait. And you might be able to take, you might want to have like a draw function that just takes a sort of list or iterator.
[24:25] of all of the things to draw. And some of those might be buttons, some of those might be images, some of them might be text boxes, but it doesn't really matter for the draw function. All it cares about is that it gets an iterator of things that are drawable, which has a similar sort of flavor to this, right, where we want to just take a slice of things that I can call high on. And what you need is what's known as a trait object. A trait object is where you see the din keyword.
[24:58] This isn't actually gonna compile. So what I'm gonna do is sort of, this is sort of what I want, right? So, imple, remember, is a shortcut for, and this is where it'll be useful to actually write out the types, is a shortcut for this. And this sort of gives a clue to what's going on. Bar is generic over one type, which has to be either a str reference or a string. It can't be both because it's only generic over one type. And you can imagine that we have like an H2 high here, but given that we're taking a slice or let's say an iterator there is nowhere to put h2.
[25:38] There is only the one iterator, which only has items of one type. So this won't really work. In some sense, what we want to say is that each of the things is a high. It doesn't have any other concrete type that we care about. And in fact, if we write this, we get a compiler error saying, let me pull this up on a new screen. It says, trait objects without an explicit din are deprecated.
[26:10] Okay, let's get rid of the warning first. It's saying we need to put din here, so we're just going to do that. And now it says, the size for values of type din high cannot be noted compilation time. So it points to this and says, doesn't have a size noted compilation type. The trait sized is not implemented for din high. Slice and array elements must have a size type. This is an error that you might have come across before. And part of what we're going to be talking about for some of the remainder of the stream is why we get this error, what it means, what the fix is, what sized means, and sort of how this ties into dynamic dispatch and trait objects.
[26:50] Let me pause here for a second because I've just thrown a bunch of stuff at you. Let's see whether it makes sense. So it's a bunch of discussion of dark mode and light mode. So really, what we want to say is, you can think of this as sort of type erasure. We want to say that I want to take a collection of things that, and I only care about the fact that they implement this trait.
[27:26] I sort of want to take an abstract notion of this trait. All right, so the challenge that the compiler is pointing out is in this case, where are we going to even start with this? All right, I think we need to talk about the sized first. So let's go to the sized trait. So the size trait has no methods. It is a marker trait.
[27:58] That's what is in the marker module. And the description just says, types with a constant size known at compile time. Now, most types are sized. Like if you create a struct foo, it's probably sized. Most types in the standard library are sized. In fact, there are very few types that aren't sized. So few, in fact, that every trait bound you have, even if it's just like a foo T, has an implicit bound of requiring that the type is sized.
[28:32] And to see why, think about what happens when, let's just sort of comment this out for a second. Let and comment this out for a second. I just want to get actually, I guess I can do this smarter. So let's sort of go back to our very simple strlen example in the very beginning, right?
[29:05] It's gonna be generic over some S that implements asterisk str. It takes that S. And it returns uSize as ref length. So imagine that something wants to call strlen. Well, strlen takes an argument that is that s. So it has to be past a thing. Like somehow it needs to be past that argument. Well, the argument that it gets past has to take up space on the stack or has to be passed in a register, either or.
[29:41] Which sort of means that the compiler has to make sure that there's sort of code in the resulting assembly that allocates the required space on the stack for whatever this argument is. And that requires that the compiler knows how large the argument is. If s here, I guess think of the concrete implementation, so strlen str. Here, this is just a, hmm.
[30:20] And let's go with the string implementation. So string is really just a, it's sort of two numbers and a pointer, right? It's the length of the string, it's the size of the allocation, and it's a pointer to the first character in the actual string on the heap. So it's size. The compiler knows that the size of this argument is three words, three. use sizes, if you will, right.
[30:52] And so we can generate the assembly code for this function and for calling this function trivially, because it knows how much space the arguments take up. You can imagine something similar, right, where if we were generic over the return type, it would need to know how much space to actually allocate for the return type on the stack. And so even though we didn't specifically say that s is sized here, it just is basically always a requirement that the type is sized. Because if it wasn't, the compiler wouldn't know how to generate the required code for it. Right.
[31:35] All right. So why. Why then is it compiling when we're trying to use this? Well, din high is really just saying anything that implements high, like just something that generates high without giving a concrete value. Because remember, we want this to be a slice of potentially like string and stir and whatever other types might implement this trait. And those are all different sizes, right? A string is two numbers on a pointer, a str is one number on a pointer, and you can imagine that we have some type foo that is like a gigabyte large as a struct or something insane, right?
[32:16] And we implement hi for it, and that is also something that we might wanna pass in here. So this slice doesn't have a size. It's just not, like if you, a slice is really just a contiguous piece of memory, right? Where each chunk is the same size. It's an array where all of them are the same size. But if we don't know the size of them, we can't guarantee that they are the same size. If I told you, if I gave you one of these, So din high here is not sized, right?
[32:47] Because it could be any type than once high, which could be any size. And I asked you, give me the fourth element. Normally in an array, because all the elements are the same size, the fourth element is just the pointer to the start plus like three times the size of one element, right? This is a pointer arithmetic to get to the fourth element. But if they're different sizes, you can't generate that code. And this is why it's saying slice and array elements must have a size type, because otherwise, the type just doesn't make sense.
[33:23] So how can we fix this? We really want to be able to do this. It would be insane if Rust didn't give you the ability to talk about things that implement a trait as a collection. And arrays aren't the only problem here, right? Even if we took, even if we wrote, what's a good example of this? Let's say we had a strlen2 here that took a like din asref str. It has the same problem, right?
[33:57] If I try to compile this, you see it says the same thing. Let me get rid of the other message. It says, the size for values of type din sRF str cannot be known at compilation time. Sized is not implemented for din as ref. Function arguments must have a statically known size. Borrow types always have a known size. And then it tries to give you a suggestion for how to fix it. But this is sort of the key insight again, that the compiler needs to know how large the type of an argument is.
[34:31] Otherwise, it can't generate the function call code. And so this is sort of like a fundamental requirement of the compiler that these types are sized. Does that make sense so far, like why this is a problem? Can you show us implementing sized? So sized is auto-implemented for any type that can implement it.
[35:04] So if you do like struct foo with no fields, it is sized. If you add a string in there, string is sized, so foo is sized. If you add another bool, this type is now still sized. Types are always sized if they can be. The exception would be if I did something like... And in fact, even if I did foo t instead of this holds a t, it's still sized because remember that there's an implicit requirement for every trait bound that it is sized.
[35:38] So there's sort of an implicit t sized here. And so that means the T is sized. So all the fields are sized. So therefore foo T is sized for any T. So you never implement sized yourself. It is only ever used as an auto trade. The issue is not stack size.
[36:12] The issue is not that it might not fit on the stack. It's that in order to call a function, right, just at the machine code layer or think of it as the assembly layer, right, in order to call a function you need to know when you call that function how much space do you allocate for the like stack variables of that function. We might include some of its arguments or on the caller side when you have to allocate the space for the return value, how large should that space be? Fundamentally, that just requires that you know how large the space is, because you can't generate the machine code for making that stack.
[36:49] There are like sneaky ways you could do this, but basically, the compiler, in order to generate efficient code, has to know the size of these things. Let's see. What things aren't sized? So we've talked about bear traits. So this is if I write pubfn foo, and I just say that I take a high.
[37:27] High here is a trait, and lots of things implement that trait, and they might all be different sizes. So this doesn't have a defined size. If I say impl here, right, impl is a shortcut for H. Hi. So this ADH is sized because we get a copy of foo for every concrete type. And for each of those copies, the size of the type is known. So if we use static dispatch here for monomorphization, this is fine.
[37:59] But if we just try to take like the trait itself, saying basically this function takes anything that implements the trait, this won't work because this is not sized. And this is equivalent to writing din hi. Like this is not sized. We'll talk in a second about how you make something like this sized. Um, the other example is something like, um, uh, if we go back to my, my struct foo, uh, if you try to have it hold a stir, uh, stir is not sized, um, because a string can be any size sort of, if you think about not the pointer to the string, but the string itself can be any size, uh, the same with like, um, This, just like a slice without a reference, is also not sized because you don't know how many elements there are.
[38:51] So it doesn't have a well-defined size. Those are the two best examples I know of, of things that aren't sized. And then anything that, in turn, contains those types. There's a lot of discussion in chat trying to explain the things that I'm about to explain on how we fix this and why you need references and stuff. I will get to it, I promise.
[39:28] Great. So I think roughly where we've gotten to so far makes sense, it seems like. So the question now becomes, how can we resolve the situation? We want to be able to take a, for our Sterling 2 here, let's call it Sterling Din maybe. We want to be able to have a method like this that doesn't get monomorphized. But this isn't sized, so what do we do? The trick here is to make this be a type that is always sized.
[40:05] And the way that we do that is by indirecting it through some type that is itself sized for any inner type. An example of this is a reference. So a reference is always the same size, it's just the size of a pointer, or in some cases two pointers, we'll get to that in a second. This does have a size. The compiler always knows how large one of these are, no matter what the type that follows is. Because this is just a pointer.
[40:40] The same would be if you have a box. right? A box, also just a pointer to the heap. And so once we do this, the size of this argument is now known, and we're fine. And this is in fact how you take something, take a trait itself without monomorphizing, is you place it behind some kind of pointer type. Like a reference, like a box, like an arc.
[41:13] The way this works in practice is that if you look at the definition of box, so it has magic in it, right? It's not magic, but it has a bunch of stuff inside of it. Basically, it just has a pointer. It's not quite true, but close enough. Box actually has this definition on it. And the question mark here means does not have to be. So it's basically opting out of the auto bound that gets added of everything has to be sized, saying for box, the T does not have to be sized.
[41:50] And that's why you can create a box of something that itself is not sized. And the reason this works is that when you create the box initially, you make an allocation that's the size of whatever you're going to put inside of the box. So let me make a main here that's going to exemplify this. At some point, I have to do box new of, say, string from hello.
[42:25] Right? And then I can say that now this is going to be a din as ref str. This should say x. And this should say str. And then I can call strlen din with y. So at some point when I created the box, I had to give it something with a concrete type. And at that point, it allocated on the heap space for that type.
[42:57] But the box is still of a known size because it's just the pointer. When I turn it into a box for this, it's still just a pointer conceptually. even though the thing it points to might have an arbitrary size. But the actual argument that we pass to this function does have a size, and therefore we can generate the relevant code. Does it make sense why indirection through a type like this where the indirection type size is known? Does that make sense?
[43:37] We'll talk about combination of traits too. Let's see. I promise we'll get to multiple traits. Can't you just put BoxedInAsteroidStir directly on X? Yeah, so you can do this too. AsteroidStir. That's also fine. But even so, you still had to provide a concrete type to Box New that was sized.
[44:16] When should we use box over references? Like when do you choose this over this? There's no hard and fast rule there. In general, the advantage of box is that it's static. So you can keep using it even after the stack frame of the caller goes away. So it's the same as when do you choose box over references normally. Can I also then give the function a reference to the stack? Yeah, exactly.
[44:47] So you can also do, let me do that down here. So I can totally do, and then Sterlendyn, why? Right. So this, let's say I have a din2 that takes this, and this can call din2.
[45:25] Why is this complaining? It's because box has an asterisk method too. That's why the double asterisk is needed. Yeah, so you see, I can do the same for something that's on the stack. I can create a sort of go through a pointer in direction here and then pass it to something that takes a referenced in.
[45:59] And in fact, I think I can even do this. Yeah, that's fine. It's not terribly important why that doesn't work. So what we just constructed is known as a TraitObject. It is an object that only has the property that it represents a trait. So this is what TraitObjects are. They are things that only behave as some underlying trait.
[46:35] This is a TraitObject, and this is a TraitObject. It doesn't matter what the wrapping type is. Box is kind of a pointer type. Yep, box is a pointer type. Can I convert a trait object to its original concrete type? I'm going to go with no, but technically yes, sometimes. But in general, no. You can think of it as, this is essentially type erasure.
[47:08] You can technically go back through like unsafe transmutes and stuff, but in general the moment you turn it into a trait object You erase the knowledge about what type it used to be But yeah, there's like some magic around unsafe and some magic around the any trait that you can use. But in general, you should ignore that. Also note that when you do this, you only retain the ability to use this trait. You erase all other knowledge of what the concrete type was.
[47:39] So the only thing you can do on a boxed in ASRF stir is call ASRF on it, nothing else. Same thing here. And we'll get into why in a second. All right. So this raises an interesting question. Let's take the example, let's make this the two and this the one, and just swap these around so this still compiles. Let's now think about what actually happens when the compiler has to generate the machine code for this function.
[48:15] At some point it has to actually do the compilation and produce assembly code that can in turn be turned into runnable machine code. So S here is some type that implements Sref. In fact, let's go back to our high trait. That's going to be a little bit nicer. So let's go back to here and let's say that I want a sayHi which takes a dinHi, returns nothing, and just calls Hi Right? So this is going to be, this takes a trait object for the Hi trait But when the compiler generates the code here, it doesn't know what type s is Right?
[49:01] It's just a trait object. It's really just a pointer. So how does it call the high method? Remember, in the generic case, static H. In this case, we actually get a copy of this for each concrete type.
[49:37] So really, this turns into this. And for this concrete implementation, generating the machine code is trivial, because this is really just like an assembly call to whatever it is, to this line, to line 6. It's not actually line, it's memory locations in the binary, but you get the idea, right? That the compiler knows statically at compile time where to go here.
[50:10] For the dynamic case, though, what do we call? We don't know that this is a str or a string, right? So we don't know whether to generate the address of this, the address of this, or the address of something else entirely. So what machine code does this turn into? Well, this is where we get into dynamic dispatch and V tables or virtual dispatch tables. So the trick to constructing a trait object is that it's actually not quite true that the reference of the box is just one pointer wide.
[50:48] It actually carries a little bit of extra information about the type that is pointed to. So here, let's go back to the, back to the the Rust book. So the Rust book has a chapter on dynamically sized types and the size trait. This is under the advanced type chapter. And what it's talking about is, in fact, it doesn't even talk about as much as we wanted to talk about. Here.
[51:22] Let's use the Rust reference instead. So the Rust reference on dynamically sized types says, most types have a fixed size that is known as compile time and implement the trait sized, like we've talked about. A type with a size that is known only at runtime is called a dynamically sized type, or informally an unsized type. And this is the slices and trait objects are two examples of dynamically sized types. The reason why this is only known at runtime is, at compile time, we don't know what type this is gonna be. It's only at runtime that we'll know.
[51:54] And we can, to make this a little bit more concrete, imagine I have a main function where if rand, I don't have a random number, random is four. If random is four, then say hi of this, Otherwise, say hi of string from world. Right?
[52:30] And let's imagine that random was more random than 4. You don't know until runtime. Let's say this was read from the user. At compile time, you don't know which actual type is going to be used here. It's only determined at runtime by some input that can't be predicted at compile time. Right? So that's why this is determined at runtime. And it says, pointer types to dynamically sized types are sized but have twice the size of pointers to size types.
[53:09] So pointers to trait objects also store a pointer to a V table. And this is where we get into what is a V table. Well, when you have a trait object, something like at din pi, what actually gets stored in the reference is one, a pointer to the actual concrete implementing. implementing type, and two, a pointer to a V table for the referenced trait.
[53:48] So then what is a V table? So a V table or a virtual dispatch table is a little data structure that has pointers to each of the methods for the trait for the type. So in the concrete case of the high trait, so let's say we have a din high, the V table is going to be sort of you can think of it as a high V table struct that only has one member, which is high, which is a pointer to an Fn, an Fn actually, that itself takes a pointer to whatever the T is.
[54:45] So basically, a different V table ends up being constructed for each concrete type turned into a trait object. So when we start out with, let's say that we have a stir, and we want to go to a din high, what actually gets constructed is a let's say we have a um Well, number one becomes a pointer to the str.
[55:16] And number two becomes a high Vtable, where high is str as high, high, and a pointer to that. When you make this conversion, the compiler knows that it has to construct this Vtable, and it sticks the address of that Vtable inside of that reference.
[55:48] So this reference contains two things, the pointer to the actual type and the pointer to the Vtable that the compiler generated during this particular conversion. So there'll be one such Vtable for each type that gets turned into a TraitObject. And so now when the compiler tries to generate this code, what it actually generates is like s.VTable.High s.Pointer.
[56:23] And so if someone passed in, say, a string instead, it would have a different Vtable. So the s.Vtable would be a different pointer. So in this case, this would be where is str high? Like line 6, right? So this would be a pointer to line 6. But if we instead went, I'll stop for questions in a second. If this instead went from a string to a dyn high, It would be a pointer to the string and string as high, which is this method up here on line 12.
[57:06] So in other words, this code that gets generated will work regardless of which type is passed in because we indirect through the V table and each type has its own distinct V table. All right, that was a lot to throw at you at once, but hopefully it wasn't too bad. Let's see.
[57:45] Are the V tables themselves statically built at compile time, or are they also allocated dynamically? The V tables are... The V tables are built at compile time, they're built statically. And so in general, the second part of the... So this is what's known as a fat pointer or wide pointer, because it has two pointers in it, not just one. So anytime you see this, it's actually a wide pointer. And in general, the second pointer in there will always be known statically, because it's determined by the original construction.
[58:23] of the trait object. The reason I say generally is because you technically can construct it on the fly. There's nothing in the calling here that requires that it was known statically. So you could imagine manually constructing a vtable. And this is used, we'll actually talk about that a little bit later. Refster also contains the length of the string slice.
[58:56] Yes. So in general, this will actually be this. So it's not a pointer to the actual string. It's actually a pointer to the str reference, which itself holds the length. Can we debug print the Vtable struct somehow? I don't know of a way to get the compiler to print its Vtable struct, but it's basically just this.
[59:33] It just, there's a member for each method of the corresponding trait that this is a trait object for, where each member is... Each member is a corresponding method, and the value is the pointer to the implementation of that method for the concrete type. Then why are trait functions that don't take self not object safe? Couldn't the compiler just generate an fn mute self that doesn't use self?
[1:00:08] We'll talk about that in a second. Does it construct a new V table every time we create an instance? No, the V table is generally statically constructed for the type. It doesn't get constructed dynamically. Are identical V tables detected? No, there's no deduplication of these. And in fact, they are guaranteed to not be duplicates.
[1:00:43] If you implement a trait for two different types, then the implementations, even if they contain the same code, are still distinct locations in the source code and in the resulting binary, and so would have different addresses. Trait objects of more than one trait we'll get to in a second. So box din is a thin pointer that points to a wide pointer that points to the object. No, if you have a box din height, that box itself is a wide pointer.
[1:01:22] So box is a little bit of a special type. Actually, it's not that special. It's just that box internally contains a mute dhinhi. And the Rust compiler knows for references and pointers that if they are trait objects, they're actually width 2. So box isn't special, but pointer types are. So box.dynhi is itself wide. You don't end up with an extra indirection. Yeah, we'll talk about nightly APIs for trait objects too.
[1:02:13] All right, so I think we're now at a point where that roughly makes sense. So there are a couple of reasons why trait objects are a little bit more constrained than being fully generic. So, for example, let's imagine that you wanted to have a... hubfn baz that took an s that is din, let's say, hi plus sref stir.
[1:02:58] And we're going to do s.hi. And then we're also going to say, let S is S dot S ref. And then we're going to do S dot high again, because we know that strings themselves implement high. I guess maybe that's confusing. Maybe I should just do len. The compiler here said, oh, it's ambiguous. All right, let's get rid of the ambiguity. It's not really relevant to the discussion.
[1:03:33] It still won't let me do it, why not? Do I have to do this maybe for it to not be ambiguous? No, all right, I'm just gonna, let's pretend that the syntax worked for a second here. So basically I want to say that I want a trait object of two different traits. This won't actually compile and ignoring the parsing error for a second, there's actually a bigger reason why this won't work, which is, In order for this to work, we need to know both where the high method is and where the asref method is.
[1:04:18] But those are contained in two different vtables. One is the vtable for high for the concrete type, and one is the vtable for asref for the concrete type. And so what we'd actually need is not just a two-wide pointer, but a three-wide pointer. A pointer to the data, a pointer to the vtable for high. and a pointer to the V table for ASRF. And that's possible. There's nothing that's sort of inherently impossible by that, but it would mean that as you add more traits, the size of this reference just keeps on growing.
[1:04:55] And that's probably not what you intended. And you might go, well, can't the compiler just generate a V table for the combination and then pass that in? That is something that in theory it could do. The Rust compiler doesn't currently do this. I don't know of a proposal. to do it. Part of the reason is because you can get around this by saying pub trait high azref and it requires that the type is both high and azref str with no methods of its own.
[1:05:28] And now I can do this. Right? Because now there's only one Vtable, and that Vtable is high ASRF, and the compiler knows when it has to generate the Vtable for this trait, that includes all the methods from both of these traits. And so this Vtable is going to be larger because it is going to have both the high method and the ASRF method. And so I think part of the reason this hasn't landed in Rust itself is because you can opt into it yourself. And by not automatically turning the plus into a larger V table, you basically tell the developer that this might not have been what you meant, but if it is, you can do this thing instead.
[1:06:12] I agree the compiler error here probably been better, right? Some in Esteban Cooper. That maybe we could sort of inform... people that they can generate their own trade here. I think it's someone wrote I think it's I plus s ref.
[1:06:52] Stir, let's see if that's true. Yeah. Okay. So, so that is the, the, the way to get the right compiler error, which is only auto traits can be used as additional traits in a trait object. Whereas here you have an example of two different traits that are, neither of them are auto traits. We'll talk about that in a second. And here it does actually give the suggestion we talked about, right? Consider creating a new trait with all of these as super traits and using that trait here instead. And it also points out that auto traits like send and sync are fine.
[1:07:27] And basically the idea here is that for marker traits, like if I want to say high plus send, send doesn't have any methods. So it's fine for the V table to be empty. And therefore we don't need to store that additional part of the V table because there aren't any methods in it. So that's why it's okay to have additional traits with no methods. I don't think you can use your own. Like if I did a Fuchs trait and I said this plus Fuchs, I don't think that'll work.
[1:08:00] But there's been some proposal of having a marker annotation to declare a trait as never having methods. But that's not something we currently have. So at least for the time being, this is the way that you should do it. Great.
[1:08:34] All right. So that is how this works with combinations of traits. But that's not the only example where trait objects are a little bit limited. So the other one is, let's imagine that for high, we added a, actually, let's start with saying that we added an associated type. Let's call it name. And we don't actually use it for anything, we just add one. The code already doesn't compile. Why doesn't it compile?
[1:09:05] Well, the value of the associated... Oh, that's the implementation. Let me do that. So this is going to be type name equals unit. Just going to use that for both of them because we don't actually care about the type. Yeah, so here it says the value of the associated type name from the trite high must be specified. So it says here where we take a din high, we actually need to specify the associated type.
[1:09:39] We can't just say we take any high regardless of what its associated type is. And the reason here is because that information can't be captured in the V table because this is a type. It doesn't have an address in the binary. It doesn't have anything we could stick in the V table. And therefore, this won't work with a trait object directly. Instead, what you would have to say is I take a high where name. is this. And I think we need to do the same down here.
[1:10:15] And then that works. Because now we have a V table specifically for anything that implements high where the associated type is name. So that's fine. Let's undo this because it's not a very interesting change. The other, perhaps more interesting case is, let's say that we want a... What are we going to call it? We're going to call it, like, weird. We're going to have a weird function that does nothing.
[1:10:48] No one needs to implement it. And you see that this also does not compile. Error in cargo check. Let's make this a little bit smaller so that hopefully it's a little easier to understand. Hopefully it's still readable. Ooh, that's very verbose. Let me comment out the combination trait bit just to make the errors a little nicer. Alright, so this says the trait high cannot be made into an object.
[1:11:24] So when we say din high, basically it's telling us that the high trait is not object safe. That is, it cannot be turned into a trait object. And it says for a trait to be object safe, it needs to allow building a V table to allow the call to be resolvable dynamically. So this is what we've been talking around through so far. And in particular, here it says the trait cannot be made into an object because the associated function weird has no self parameter. It doesn't really talk about why that's necessary though. But let's try to work through it.
[1:11:56] So again, let's say that down here in our sayHi, right? We now try to call s.weird. So imagine what would the compiler do if we wrote this code? Well, we can't really write this code, right? Because weird doesn't take self. It doesn't take a pointer to anything. And we can't just like randomly construct a pointer to it because that would mean that we need to have a valid instance to it to have a pointer to it.
[1:12:28] So this is really just saying like, then hi, like colon colon weird. which I don't have to tell you seems weird because which type are we calling weird on here? There is no, like nothing here specifies which actual weird implementation we want. In this particular case, because it provides a default, you might think it's not a problem. Well, what if there was like an implementation of weird for string?
[1:12:58] that was different from the one on the trait, which is allowed, right? You can override a default implementation. Well, how would this know whether to call the one for str or the one default for the trait or some entirely different one? It can't be in the V table because there is no S here, right? The weird method doesn't take itself. It's not associated with any given instance of any type. So this just doesn't work. It's not a meaningful thing to say.
[1:13:32] But what if you really wanted this? Like you wanted the weird function to exist, but you're like, I don't care about calling this through a trait object. I only care about the high thing. through a trait object. So I want high to be trait object safe, but if you have a trait object high, I'm fine if you can't call it weird. So you can do this. this.
[1:14:09] And let me go back down here, have the speed in high again, s dot a. So. What we're saying here is that the weird function requires that self, that is the type that implements the trait, is sized. And we remember that traits aren't sized. If you just have like din high, that's not sized. It's only sized if it's behind a pointer type.
[1:14:43] So this is basically a way to opt out of the V table is the way that you can think about it. It's saying this function shouldn't be placed in the V table and crucially shouldn't be callable through a trait object. What this means is in here, let me get rid of the static versions because they're just in the way. What this means is now the code compiles just fine. I can call hi, I can make a trade object for it. But if in here, in fact, I can go even further and say, let's say that this did have a self, but I wanted to opt out.
[1:15:22] then this still compiles, I can still make a trait object for it. But let's say that I try to call weird in here. the compiler is gonna tell me the weird method cannot be invoked on a trait object because the method has a size requirement. And so this is the way to opt out for any given function from having it be included in order to make sure that the trait remains object safe. You can also say that the entire trait should not be possible to turn into a trait object by saying where self is sized.
[1:16:01] So if you do this, you're basically disallowing using this trait as a trait object. It's rare that you see this in practice. Usually the trait will, like the trait just isn't object safe because of the methods in it. Opting into disallowing trait objects is rare. Sometimes people do it for... backwards compatibility reasons. Like if you know that you might add non-object safe methods later, you might add this proactively, but it's pretty rare.
[1:16:36] All right, do the restrictions so far make sense? Does the associated type problem also occur with static dispatch? No, it doesn't. And the reason is with static dispatch, because it gets monomorphized, you actually know the concrete type for any given function implementation. s colon colon weird could be possible.
[1:17:10] So this is back when we had the fn weird, right? And let's say we also had an override here. And now let's say you wanted to be able to like, let's say we added like special syntax like this saying for the type of s called the weird method. you could imagine that weird got included in the vtable for the trait object, but it knows to not call it with a self argument. The challenge here is that this is sort of odd.
[1:17:45] If you require an instance of the type anyway in order to call it, then why doesn't it just take self? The traditional example of this is that weird is actually called new or something like new, right? Where it doesn't, if you already have an instance of the type, you wouldn't need to call the method in the first place. It would just take self. So I agree like something like this maybe could be possible. I think in practice, it's just not usually very useful.
[1:18:19] And that's why it hasn't been a priority. There might be a deeper reason why it's not added to. I'm not sure. um um does where self colon sized also disallow implementing the trade for concrete dsts um You know, that's a good question. So the question is basically, if you have where self is sized, can I implement high for box din as ref stir?
[1:18:58] for example. I believe I can. The reason I say this should be possible is because, yeah, this now won't work because it can't be a trait object, but you can still have this implementation, I believe. Why does this? Oh, right, because it's a box. So we need to have the double sref. This is fine because this is not a dynamically sized type.
[1:19:35] Again, when you wrap it behind a pointer, it now has a size. It's not dynamically sized. So it doesn't prevent that, even if you have self-sized on the trait. The associated type restriction feels weird because the point of associated types is that only one exists for any given concrete type. So shouldn't the V table know what the associated type should be? Like, it can't have a pointer to the type, but the implementation of the trait should know what the type is when it's compiled.
[1:20:07] Yeah, so the problem is that the type is erased. All that remains is the V table. And so you can't tell from the V table what the concrete type used to be. There is an exception to this, which is the any trait. So the any trait has a method that returns... turns a descriptor of the type of the concrete type that it used to be. If you didn't follow that, that's fine. Ignore it. But basically, there are some ways to sort of finagle around this. But basically, trait objects are type erased.
[1:20:38] Like you don't get to keep information about the type it used to be. Oh, you meant type such as str or u8. No, you can't do that. Self has to be sized when you have where self is sized. There's one other restriction that you get with TraitObjects, which is that the methods cannot be generic. And for this, rather than sort of keep working on our weird high trait, I'm actually gonna go to the standard library and look at the fromIterator trait.
[1:21:16] So the fromIterator trait is something that's implemented by Vec, for example. This is how collect works, is that Vec implements fromIterator. And when you have, well, So if we look at iterator collect, I guess is the best way to do it. Collect on an iterator requires that the thing that you collect into implements from iterator. So that's why you can have an iterator and collect into a vec, it's because vec implements from iterator. The from iterator trait is a little weird though. The A type of the trait is the type of the items of the iterator.
[1:21:55] but you also see that the from iterator type itself takes a T. And the T here is the type of the iterator, right? Cause it has to be vec, for example. It doesn't care what the iterator is. It can be, it can, you can construct a vec from any type of iterator, as long as the, well, you can create a vec T from any iterator where the item is T. This arguably should be called I for iter, but it's not terribly important. Here, where a is the sort of thing that you'll end up with a vec of.
[1:22:30] So if this a was, say, bool, you would end up with a vec of bools. And the t is the type of the iterator, which might be something like, I don't know, like a HashMap Intuator or whatever that type ends up being. This poses a problem for a Trait object, though. Let's imagine that we try to write code against this. So I'm going to erase this for a second. In fact, I'm going to write a new one. erase all of the remainder of this file. Then I'm going to have like, what are we going to do here, let's do collect.
[1:23:09] Standard iter from iterator, we're going to take a from iterator of bool. And we're going to return a vec of. And I'm going to do s dot collect. Ooh, what did I do? I did something weird, didn't I? Great. So this seems like it should be fine, right? I take anything that can, I take.
[1:23:42] Well, actually, this is weird for a number of reasons. Maybe fromMeterator is a bad example here, because it doesn't take self either. So it actually requires self to be sized anyway. Extend is a better one. Let me dig up extend here. Great. So we're going to use extend instead. and it's going to have to take a mutant. And so we're going to do that mute v is back new, then we're going to do v dot extend.
[1:24:18] Actually, we're not even gonna do that we're going to take this is going to be the V, we're going to do v dot extend, and we're going to give it just it are once true. So we're going to just extend it with a Extend with a single bool, add true. So we take in anything that can be extended with an iterator of bools. And then we try to extend it with an iterator that yields a single bool.
[1:24:49] So we're just gonna add true, we're gonna append true to whatever thing we get. And here too, it tells us the trait extend cannot be made into an object because extend is not object safe. And if we look at extend, that doesn't immediately make sense from what we've seen so far. Right? So again, it's generic over the type of the items of the iterator. That's fine. Extend takes self. So we do have something we can stick into the V table. And given an instance, we sort of know how to call this method. But again, notice that it's generic over the type of the iterator.
[1:25:23] And this is where it gets really weird. you can imagine the like inside of vec, right, there's going to be imple t, extend t for vec t. And it's going to have this implementation. I'm going to go go ahead and call this I because I think it's more helpful. And who knows what's going to be in here, right?
[1:25:58] Yes, just to get rid of that warning. Uh, I'm going to do this. Um, I guess be a little bit more helpful. My vec. Like this implementation is going to exist somewhere in the standard library, right? Except just for vec instead. But this method is generic. So we know from the monomorphization discussion that actually at compile time, we don't end up with a single extend.
[1:26:35] We end up with multiple copies of this method. Right? We end up with like an extend rule that takes... Now, an extend, I guess, HashMapIntoIter, which takes a standard collection HashMapIntoIterator. Right? And in fact, even more than that, we're actually going to end up with, because the whole impl is generic, we're actually going to have this.
[1:27:13] That is the actual method that gets implemented. or get sort of generated by the compiler, assuming that someone tries to extend using a HashMap iterator of bools. There is no one extend. There is one for every combination of iterator and item types. So what gets put in the V table? We've nailed down that we want to extend bool.
[1:27:44] So that's good, right? So there's only, we don't have to consider the T up here because we've already chosen that T. But for extend itself, we really, in the V table, really needs to have a pointer to extending for this iterator type over bool. but that's not expressed in the type of the function. And we don't even have a way to express it. Right, you could just sort of imagine like where, like these implementation of extend is standard iter one spool or something super weird like that.
[1:28:26] But the way that it's written, nothing here says that we want the Vtable to point to the extend implementation for a standard iter once. And therein lies the problem. When the compiler tries to generate this code, there is no pointer to the appropriate implementation of extend. Therefore, the V table can't be generated. You can't generate a V table for dinExtend because it would have an infinite number of entries, one for each possible implementation of extend.
[1:29:02] And so therefore, the answer is just dinExtend cannot exist. You cannot create a trait object for extend. All right, does that make sense? That's a somewhat intricate explanation, but hopefully it all sort of ties together here. Um, could Rossi add a monomorphized version of extend extend for each T it's called with to each type that implements extend that's tempting, but it's not always possible, right?
[1:29:36] So imagine that you're compiling this code, but, um, I mean, even just for the standard library, right? Like the standard library has a bunch of uses of extend, but in crates that depend on that crate, they might call extend with even more types. So the size of the V table, like when you compile the bottom most crate, if you will, like the standard library, essentially, that would mean that the V tables for din extend in the standard library is different than the V table for din extend in crates.
[1:30:12] other crates further up because there are more possible iterator implementations that you might want to use. And so you now would end up with lots of different vtable implementations or lots of different vtables for dinExtend. And that's like it would be a combinatorial explosion kind of problem. And it would also mean that you can't pass a dinExtend from the standard library to a thing that takes dinExtend in a crate further up because their vtable types are different. All right.
[1:30:54] So this is the reason why you can't have... In order for a trait to be object safe, it needs to... not have generic methods. It needs to, all of its methods need to have a receiver that includes self. And there's another requirement, which is that the trait can't have a type that returns self. So if we backtrack a little here and say clone, and we wanna take a thing that is didn't clone, and we're just gonna, call clone because it's the only thing we can do with a din clone.
[1:31:37] Right? If you have a din clone, you can literally only do the things that the trait lets you do, and the only thing clone lets you do is clone. So this says the trait clone cannot be made into an object. This is now an error that we've seen a decent amount. The reason why you can't do this is because the clone trait, right, has a FN clone that takes self and returns self. Alright, so let's say I say let x is v.clone. What's the size of x? Didn't clone is just any type that is clonable.
[1:32:16] And it's supposed to return self, like not the reference. So it's not supposed to return a reference DynClone. It's supposed to return self given a reference. So that sort of means that it should return DynClone because that's what self is here. Because we've erased the concrete type. But DynClone isn't sized. So it would mean that the return value of this method isn't sized. And the return type of a... function must be sized for us to generate code for it.
[1:32:49] Therefore, this can't work. So you can't have methods that return self for a trait to be object safe. And that's why you can't do clone. Now, there are some cases where you have a trait where, as we talked about with high, you might have some methods that are object-safe and are still useful on their own, but you have a bunch of other methods that would make the trait non-object-safe, but you want to include them for types that aren't going through a trait object, just because it's convenient.
[1:33:23] And in fact, a good example of this is if we look at the iterator trait. So the iterator trait... right has the associated type item that's fine it has next and next is object safe but it also has a bunch of methods like chain which is generic it has enumerate which returns self it has By ref, which returns mute self.
[1:33:56] It has collect, which depends on from iterator, which we already know isn't object safe. So how can iterator be object safe? Because it is. If I say it here, and I say I want to take a din iterator where item is bool, we collect. Oops, iterator. Well, I can't call collect because this method cannot be invoked on a TraitorObject.
[1:34:30] But I can call next. I'm allowed to call next on this. Mute, otherwise it doesn't work. That works fine. And the way that the iterator trait has achieved this is that if you look real carefully, you'll see that, if I actually go to the source of the iterator trait, you should see this, you just find here.
[1:35:03] So count, for example, which consumes self, right? So it's not allowed to go behind a reference, which would make it sized, has where self is sized. If you scroll down to last, which is the same, self is sized. If we look to chain, you see the chain, which is generic, so normally would make the trait non-object safe, has where self is sized. And the reason for this is you can basically, this is the same thing we did for the weird function, right? You can use the where self is sized bound to say ignore this function for the purposes of using this trait as a trait object.
[1:35:41] Basically, don't try to put it into the V table. What that means is if someone has a trait object, they can't call the method. But if they don't have a trait object, if they actually have like a vec intuitor or like they have the concrete type, then they can call this method. And so this is a way to have a trait that has some methods that are nice to have, but wouldn't be object safe without making the whole trait object not object safe. Um, can the receiver be anything that includes self or does it have to be ref self or mute self?
[1:36:16] Um, so the rules for this are actually, uh, where do I have this? I have it open somewhere. Give me a second. Here. So this is from the Rust language reference on object safety. And in fact, by now we've covered most of these things. All the super traits must also be object safe, right? Because we construct a V table from the union of all the super traits. Size would not be a super trait.
[1:36:47] So that is, if we require self colon sized, it's not object safe. Must not have any associated constants. This again is because. you don't have anywhere to put the constants. Theory, maybe you could put them in the V table, but now the V table becomes really large. And also the values in the V tables are no longer all like function pointers. They might be arbitrarily sized things. All associated functions must either be dispatchable from a trait object or be explicitly non-dispatchable.
[1:37:19] So dispatchable functions require that they don't have type parameters, so they're not generic. They have to be a method that does not use the self type, right? The concrete type, except in the type of the receiver. So this is we can't have something that returns self, for example. It can't have a receiver with anything but the following types, right? So it can be a reference to self, it can be a mutable reference to self, it can be a box self, RC self. ArcSelf or PinSelf, PinToSelf rather. So anything that's behind a pointer, basically anything that can take, anything that can turn something that's not sized into something that is sized.
[1:37:55] And you can see that explicitly excludes where self is sized bounds so that you can have an object safe trait even if some of the methods aren't object safe. This is the non-dispatchable functions. Um, should library writers always consider adding where self is sized to non-objective methods, just in case someone downstream wants to use it as a trait object? I think yes. Um, It depends a little bit on whether your trait is even usable.
[1:38:28] So if your trait isn't usable as a trait object, like think of clone, right? Then sure, you could add where self is sized to the clone method so that people could create a trait object clone, but they wouldn't even be able to call the main function of that trait. So it's probably not worthwhile. But I do think that in general, if you have a trait where it is useful, even if you... could only call the ObjectAve methods, then it might make sense to opt out for the other ones so that the trait overall is ObjectAve.
[1:39:14] Did iterator last have the sized restriction? I think iterator last does. Um, the reason why last, uh, has where self is sized, you can't see it here. It gets hidden by rust doc, um, is because it's receiver. It doesn't go behind a reference. It consumes self, uh, which means that it takes self, um, and self is a din iterator, which is not sized and function arguments must be sized.
[1:39:47] Therefore last can't be called through a trade object. There's one more thing I haven't told you. Well, there are many things I haven't told you, but there's at least one when it comes to trait objects, which is that there's a little bit of a secret with trait objects. So let us say that I have pub trait. Actually, let's do this. This is a, drop is actually object safe.
[1:40:19] You might think that it's weird. Like if all you can do with an object is drop it, then is it really that interesting? It turns out this is useful in a couple of situations. Like I know Crossbeam does this, for example, where you want to do garbage collection, but you don't want to drop objects immediately. You want to like stick them in like a linked list or something and then periodically go and collect all the garbage. Because you want to store lots of potentially different things in one type, you need TraitObjects. And so it just stores mute in drops, or I think technically boxed in drops, but same effect.
[1:40:56] You can't actually do anything with this. But here, when v goes out of scope, dropDrop is called through the btable. This should make you go, wait a second, because let's go with our sayHi. We take the dinAsRef.stir. Or actually, let's even go with boxed.
[1:41:30] It's better. What happens when s goes out of scope? Think about this for a second. We get a box, so we have a memory allocation on the heap. We might use that in here, might call s.asref, which could be high, whatever. But then we drop s when this function returns. But when we drop a box, we have to free the memory. But this is a trait object, so the only method it has is asref.
[1:42:06] The answer to this is every Vtable includes drop. You can sort of think of this as like an implicit drop here, but in practice, the Vtable for any TraitObject includes a pointer to the drop function for the concrete type, because it's just necessary. It also technically includes a little bit of extra information. It includes the size and alignment of the concrete type. The reason those are in there is because for something like a box where you have to deallocate the memory, that information is necessary to pass to the allocator to do the deallocation.
[1:42:44] And so every trait object includes the V or the V table for every trait object includes the methods for the trait plus drop plus size plus alignment. Normally, you don't have to think about this, but it's just worth knowing while we're on the topic. To shift gears a little bit, so far we've only really talked about trait objects, but there are other types that aren't sized. So for example, we know that din trait is not sized, but u8 is also not sized, and str is not sized.
[1:43:20] This one gets turned, when you place it behind a reference or a pointer, gets turned into a tuple of a pointer to the data and a pointer to the vtable. This one, if you make it sized or put it beyond a pointer, also becomes a wide pointer, where one is a pointer to the data, but the other is just a u-size, which is the length of the slice. And same thing for str, as a pointer to the data and a u-size of the length.
[1:43:57] So this is why, if you try to write a function foo that takes a u8, the compiler is going to yell at you and say that the size for the value of type U8 is not known. Because U8 this is just saying an arbitrarily long list of U8s, which is not sized. Therefore we can't call the function with it as the argument. Same as if you try to return just a straight up U8 sequence, right? If I had a bar, which returned a U8.
[1:44:33] Um, it also complains. Oh, uh, is it even going to let me do that? There we go. I constructed the type. So here it says the same thing. The size for the value of type U8 cannot be known, and the return type of a function must have a statically known size. So this is the same problem. And here too, the way that we go from something that isn't sized to something that is sized is we place it behind a type that can sort of mask the uncisedness, which you do with a reference, or you can do it with box.
[1:45:14] So you can also do box of this. I think I'm allowed to do this. Great. So this is fine because it's now sized. The size of it is a pointer that is wide, where one part is the data and the other size is the length. Um, and the compiler then knows that when you access, uh, this type, it knows to sort of deconstruct the pointer to get the length.
[1:45:51] Um, same with something like box or, or raw pointers for that matter. And same for string. So these are a little bit magical. There's been some work on trying to standardize this. So currently the sort of dynamically sized types are a little bit special in the compiler because you need to know whether the pointer is sort of wide or not. So it's fairly hard to sort of deal with unsized types yourself. Like if you wanted to implement box yourself and take a type that wasn't sized, It's possible.
[1:46:27] It gets pretty annoying once you get into casting and allowing trait objects and stuff. But there was recently an RFC that landed. RFC number 2580. which talks about adding a generic API for manipulating the metadata of fat pointers. So this lets you do things like say what the type of the second part of the fat pointer is. Right. So in the case of in fact, we can scroll down here a little and look at a DIN trait now becomes a pointy where the metadata is DIN metadata.
[1:47:09] And we're DIN metadata. is a pointer to a Vtable that represents all the information such as type size, type alignment, a pointer to drop and place, and a pointer to all the methods for the type simplification of the trait. So exactly what we just talked about. Similarly, you could imagine that this pointy trait would be implemented for something like a U8 slice without the reference, where the metadata would be a U size that is the length of the thing.
[1:47:44] This is still very much like new and experimental. I do recommend you read through this RFC. It's really fascinating if you want to learn more about this. It has things like the trait alias thin, which is any type that implements pointy where the metadata is empty, which would be anything that doesn't have associated metadata in the pointer, so anything that is a thin pointer and not a fat pointer. And it has essentially methods for introspecting the metadata of a pointer, so that you can do things like actually look at the Vtable.
[1:48:16] There was some questions about this in chat earlier. This RFC would actually let you introspect that information and crucially construct Vtables on the fly. So you could have one that isn't known at compile time, but you build at runtime. And in fact, this already is something that exists one place in the standard library, as far as I know, which is for wakers in sort of the land of async. So the waker trait, we're not going to go too much into detail, but the waker trait, which I'll show you here.
[1:48:48] Um, the waker that's I'm lying. I mean the wake trade, uh, awake, not the wait, the raw wakers. Oh, there isn't a trade for it. That's why, um, let's go show you context actually. So context gives you a waker. Waker is a struct that has the methods wake, wake by ref, willWake, and fromRaw, and you can drop it and clone it.
[1:49:24] But in practice, waker is really generic. It's just that it isn't generic when you look at it. But inside of a waker is a raw waker. And a raw waker, if you look inside of it, is a data pointer and a vtable pointer. So it really is a data pointer. is dynamic dispatch but in sort of a hidden way and the vtable is a raw waker vtable and a raw waker vtable you construct by giving the function pointers for the clone method, for the wake method, for the wake by ref, and for drop.
[1:50:03] And so it's basically a manually constructed Vtable that gives you dynamic dispatch through a type rather than a trait. I'm not gonna go into too much detail of this, but I just wanted to show it as like an example of a manually constructed Vtable in the standard library. Is there anything more I wanted to talk about from here? I don't think so. All right, let's do questions because I've rented for a little while.
[1:50:38] I thought a reference to U8 had a start pointer and an end pointer, not a length. I think it has the length. It doesn't, the two are basically equivalent. You might be right, I forget. In fact, I wonder whether this reference says. Yes, you see, this RFC also deprecates the Trait object. stuff that exists in Nightly, because this is a replacement.
[1:51:11] Pointy trait, thin metadata, from raw parts. Where is the definition of... Oh, it doesn't actually give. Yeah, I was hoping it would say here what the actual associated metadata type is for slices, but I don't see it.
[1:51:42] I think it's just the length. Can we make our own types dynamically sized types? Sort of. So you can write this. foo here is now not sized. In fact, you can add more fields. You can't add a field after though. After this is not sized, right?
[1:52:14] So if I tried to do this, it'll tell me the size for values of u8 cannot be known at compile time. Only the last field of a struct may have a dynamically sized type. Change the fields type to have a statically known size. borrow types always have a statically known size. So what this is getting at is, if it's the last field, then think back to the argument I made very early on, right? If you have a non-size type in the middle here, and I asked you, like, if I want to look up like foo.x, and you only have a pointer to foo, how do you get a pointer to x when the type in the middle can have an arbitrary size?
[1:52:54] And the answer is you can't. You don't know how to get the address of x because t is arbitrarily sized. But if it's at the end, then it's fine. You can statically know the offset of f, the offset of x, and the offset of t. And the only information that's needed in order to make this sized would be the length of the last field. And so you are allowed to construct a type like this. This type is now not sized. But if you have an at foo, then that type will be sized by storing the pointer to the foo alongside with the length of t.
[1:53:34] So you can create your own dynamically sized types this way. Is box U8 the same thing as a vec U8? So this is if you have a box of a U8 slice, not behind a reference, is vec U8. They're not the same. So no. I guess let's do this.
[1:54:05] They're not the same. They feel the same, but they're not the same. Oops. Evacuate can grow. So evacuate, first of all, has, it's three words. It's the pointer to the vector on the heap. it's the length of the vector and it's the capacity of the vector. And this is so that if you try to push below the capacity, the length just gets incremented. If you try to push beyond the capacity, then the entire vector reallocates itself, copies over, and then changes.
[1:54:39] With a box U8, you can't do that. This will never grow or shrink. You can't push to it. It's just, think of it as a, it really is just a slice. You can turn a Vecuate into a Boxuate. And you can also go the other way around. But they're not the same, no. What's the difference between a dinfn and an fn?
[1:55:28] So basically, I can write a fnfoo that takes a dinfn. And I can write an fnbar that takes an fn. What's the difference between these? These are not the same. This has to be a function. It can't be a closure. And the reason for this is fn is really a function pointer.
[1:55:59] Like it's just a single pointer that has to be an address. This is a vtable. It's a trait object, which means that it both has a sort of the vtable you can think of here has a pointer to... calling the function, but it also has a data pointer, right? Because the the V, the structure of this is that it's a wide pointer, where one part is the V table, which has the pointer to call actually calling the function, but the other part is a data pointer. And crucially, the difference here is that if I have fn main, I can call foo with a closure.
[1:56:41] So I can do a function. This, but I can't do the same with bar. Why is it complaining? Oh. Right, so I can call foo with a closure because this captures x, right?
[1:57:16] So it's not just a function pointer, it's a function pointer and the data that the closure captures from its environment. That is, it needs to, when you call the closure, you also need to supply the address of x because it's needed by the body of the closure. and that's what's passed in the data part of the wide pointer. For bar, it requires an actual just function pointer, which means that you can't pass a closure because you wouldn't have anywhere to stick the data. When we use dinfn over implfn, yeah, so there's also bazf implfn.
[1:58:03] Um, and I can call Baz with a closure. What is it? What's it complaining about? I can call baz with a closure because remember, implfn is sort of sugar for a generic function over anything that is fn.
[1:58:34] So we actually get a concrete copy of baz for every type of closure that's passed in. And therefore, you can trivially pass in the data as well because it's monomorphized to each individual closure. The question then becomes, when do you use a dinfn, when do you use an implfn? The basic answer is... Implafen is more generally usable. Like you don't have to indirect behind a pointer, for example. But you end up generating a copy of Baz for each closure type you pass in, which might become quite a lot.
[1:59:12] And the other reason is because sometimes you want to take a trait object instead of making it generic because otherwise you have to propagate the generic type up. So imagine that I had a... struct wrapper, then internally I want it to contain a function pointer. If I have it hold, like I could write this, right? I could do this, but this means that anyone who wants to, any user of my library that wants to hold a wrapper would also themselves need to be generic over f or name the type of f.
[1:59:51] Whereas if this instead stored a box din fn, the now wrapper is no longer generic, so my callers don't have to think about and propagate that generic parameter. So sometimes it cleans up your interface and makes it just nicer to use. There's also the example of trait, making traits object safe. So if I have a trait x that has an fn foo, If I make this take an impl fn, then x is not object safe.
[2:00:28] I couldn't write a crocs. I guess let's have this take self. the trait x is not object safe because this is generic. implfn is equivalent to saying f is fn and this is f.
[2:01:01] And this cannot be made object safe like we talked about. But on the other hand, if I made this dinfn, It can be object safe because there is only one foo, right? So we don't have this problem of you need an infinite number of entries in the V table, there's only one foo and it itself takes a wide pointer, which then works for any type that can be a object safe. So there's not a clear cut answer here. Um, Nice.
[2:01:49] Okay, I think, I think that captures... everything I wanted to talk about. So the one thing that we didn't get around to talking about is coherence. I think coherence is different enough that we're not going to talk about it this stream and I might just do a separate stream on it, especially because we're on like the two hour mark. So I think this is a good time to stop.
[2:02:22] and then just do this separately. Are there any sort of questions towards the end about all the stuff we've talked about so far? Is the general difference between static dispatch and dynamic dispatch, the size trait, V tables, object safety, wide and fat pointers, does all of that roughly make sense now? Or is there anything more I can go through to sort of help crystallize it in your mind and make it clear why we have these, what they're for, what their limitations are? I'm happy to take some questions towards the end here.
[2:03:00] Could runtime trait detection be implemented in the future using a types of vtable? If I understand your question correctly, I don't think it can. So the idea is that can you take a trait object or can you take a wide pointer and figure out which traits it implements just by looking at its V table? I don't think you can. Part of the reason is because a different vtable gets generated for each trait object.
[2:03:37] So it's not like there's one vtable for str or for string, right? There are many vtables for string. There's one vtable for string for each din trait, right? Um, and so there's not just one, one V table that you could then look at to figure out what, what traits it implements. Um, like if you had like a find traits that took an S that was a din, like didn't trait, um, then the only things in the V table would be whatever methods are on the trait that you name here.
[2:04:24] You wouldn't get a V table of all possible methods on the provided type. So no, I don't think you can do dynamic detection of which traits something implements this way. Does calling a dinfn involve a double dereference, once for the Vtable pointer, once for the actual function pointer within, or does that get optimized away? So if I do call takes an F of Fn, and in here I do F.
[2:05:07] You know, that's a good question. I think it'll end up being a double D reference because you first have to go through... It's not quite a double D reference because this is a wide pointer, right? It's not, it's not a pointer to a tuple of a pointer and a V table, right? It it's really what gets passed in is a pointer to some T.
[2:05:39] You just don't know what the T is and a pointer to T's FN V table. That's really what's passed in here. And so this ends up calling like Vtable.call of t. And so there is a dereference here. Like, this is a pointer to the Vtable.
[2:06:12] So you do have to dereference the Vtable. I guess this is a better way to sort of type it out. So you do have to dereference the Vtable to get to the call. It's really, I guess, this, right? You have to dereference the V table to find the address of the call that you then call. So it does end up being two dereferences, but it's not quite pointer chasing either. It is true.
[2:06:58] Okay, so there is one thing that's a little bit funky, right? Which is if you have an X that takes an S of, let's say, din S ref str, then one thing you could do, and this was mentioned in chat, with the new pointer Vtable dynamic metadata RFC, you could imagine like, if s.Vtable is equal to string as din asrefster.Vtable, then like, s as reference f s dot data as reference to string dot i guess if this was a mute uh dot push right like maybe you could do some really weird ugly magic like this
[2:08:02] I would recommend just don't do it. But yeah, you could imagine you could compare V tables this way. I don't know if this is even a guarantee that the compiler will uphold that a type will always have only exactly one V table. And yeah, the compiler does do a decent amount of optimization here too. Like if you do a box din FN, I think it like might not do a heap allocation always if you like, if just like escape analysis and stuff. But in general, if you use generics, like if you use an actual generic type parameter or an impl block, sorry, an impl trait, In those cases, you will get better optimization just because the compiler gets full insight at compile time into what all the relevant types are and can co-optimize based on the actual concrete implementations.
[2:08:52] Whereas once you have indirection through dynamic dispatch, the compiler loses some of the information it would otherwise have and be able to optimize based on. Can you do a quick example of the sliceVec of DINs? Oh, yeah. Say hi's. So if you actually wanted to do like, I guess we had DIN hi, but let's make it DIN asref stir. Then you wanted like for H and S.
[2:09:27] Let's make it V. For S and V, S.asref. Um, so to actually get this to work, uh, what you end up with is you have to do this, um, to make the sized, right. Um, so that all of the elements of the array are the same size because the raise required that so that you can find the given index. Right. Um, and once you do that, um, the salt just works.
[2:09:59] And you could put a box or arc or whatever for the inner type too. Different compilation units can lead to different V tables. That sounds about right. So this is a little bit anecdotal, but when you compile Rust code, Rust might compile one crate using multiple independent threads to compile different subsets of the crate to sort of speed up compilation. But because you want those separate units to work in like entirely concurrently without too much synchronization, they might both encounter, let's say, a...
[2:10:37] string being used as a din-asref, they might both generate their own vtables because they don't want to coordinate about generating the vtables and therefore you have multiple vtables even for the same type for the same trait. So that's one example why that invariant might not hold. That's a good point. And yeah, there is also any, which I haven't talked about. I'm not going to actually demo it, but so there's the any trait. And any is super magical.
[2:11:09] It's not actually like any is just a trait that has a function that returns an identifier for a type. that is unique, guaranteed by the compiler. And so if you have something that's a trait object over any, you can use type ID on it because it gets added to the V table to get a unique... type identifier for that value and then you can use that to downcast from a din any to the concrete type because we know what the type identifier is i'm not going to go into any too much but but any uses a lot of the stuff that we've talked about so far to actually be able to go from a din a dim trait as long as that trait includes any into a reference to the actual underlying type.
[2:12:02] It's really cool and actually surprisingly simple now that you know what you know. So I recommend you give a read to the standard AnyModule documentation. It talks about why this is safe. Alright, I think we're going to end it there. 2 hours and 15, I'm pretty happy with that. We covered a lot. I hope that was useful. I hope you feel like you learned something and some of this might actually stick. I have made a little bit of progress on my coding live stream that I really want to happen.
[2:12:36] I'm hoping it'll happen sooner rather than later, but it has not escaped me. I'm still on the case. Thanks all for coming out and I will see you next time. So long farewell!
Open in the Vidleaf workbench
Search the transcript, select lines, copy quotes with timestamps, translate.
Open this transcript in the workbench →Read your own YouTube link
Attribution
"Crust of Rust: Dispatch and Fat Pointers" by Jon Gjengset (https://www.youtube.com/@jonhoo), licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Source video: https://www.youtube.com/watch?v=xcygqF5LVmM. This page is a text transcript of the video with paragraph breaks and timestamps added; the creator is not affiliated with and does not endorse Vidleaf.
Are you the creator or a rights holder? Request a correction or removal: copyright@vidleaf.app (see About these pages).
Last updated