top | item 43491256

(no title)

kd5bjo | 11 months ago

It's worth noting that this post is 8 years old, and some things have moved on since then.

In particular, trait object upcasting is on beta now and will be promoted to stable in a couple of weeks. I know that there has also been active development towards enabling multiple-bound trait objects, but I don't know what the status of that effort is.

The article also makes the (quite understandable) mistake of conflating a fat pointer to a trait object with the trait object itself. In Rust, trait objects are "unsized", which means they can only exist behind some kind of pointer. And any pointer in Rust that targets an unsized type grows an additional metadata field (for trait objects, a vtable pointer). This is a slightly weird behavior with a few unexpected consequences that often catches people off-guard, but understanding it is key to understanding why you can't make a trait object for something like `Clone`, which returns an instance of itself-- Because unsized types can't appear on their own, the return type of the `clone()` method would be invalid.

For a more thorough take, I recommend "A tour of `dyn Trait`" ( https://quinedot.github.io/rust-learning/dyn-trait-overview.... )

discuss

order

cyco130|11 months ago

I've long entertained the idea of a language feature that allows returning unknown sized objects by value. The calling convention would generate two function calls, one to go get the size which would then be passed to alloca to reserve space for the return value and a second call to get the actual result. Not sure of all the implications but I think it might be an idea worth pursuing to make things like variable length arrays and structs with flexible members near-first class constructs in the language. Pseudocode:

   function zero_filled_int_array(length: usize): int[length] {
      ...
   }
The int[length] bit determines the return value of the size call and the main body constitutes the part that actually fills in the value.

steveklabnik|11 months ago

In my understanding, Ada allows you to return unsized values, but it's generally implemented via a secondary stack.