# Idea: Fixed sized traits

**URL:** <https://internals.rust-lang.org/t/idea-fixed-sized-traits/12179>\
**Category:** language design\
**Created:** [April 17, 2020, 3:43pm UTC](https://internals.rust-lang.org/t/idea-fixed-sized-traits/12179 "2020-04-17T15:43:50Z")\
**Posts on this page:** 1\
**Showing post:** 8

<div class="post-metadata">

**Author:** ![JeffBurdges](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jeffburdges/32/2116_2.png) [@JeffBurdges](https://internals.rust-lang.org/u/JeffBurdges)\
**Post date:** [April 19, 2020, 1:28pm UTC](https://internals.rust-lang.org/t/idea-fixed-sized-traits/12179/8 "2020-04-19T13:28:13Z")

</div>

We should imho leave `dyn Trait` unsized but instead use small box optimizations, although our current [`smallbox`](https://github.com/andylokandy/smallbox) crate [wastes one `usize` unnecessarily](https://github.com/andylokandy/smallbox/blob/master/src/smallbox.rs#L66-L70).

You instead want a `SmallBox<T,Size>` type that determines whether its internal `Size` holds `T`, or whether the first `usize` contains a `Box`, by invoking `mem::size_of_val` with the vtable provided by `dyn Trait` and `ptr::null`, ala [https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=9f175095c2f072317c31d3e5c68e291b](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=9f175095c2f072317c31d3e5c68e291b)

It works because `mem::size_of_val` never dereferences its data pointer. All `dyn Trait` record their size n their vtable. We cannot create `dyn Trait`s from unsized types, but even those keep their size in the fat pointer.

We'd make `alloc` an optional crate feature, so this `SmallBox` crate still works without std or even alloc. At this point, you define an error type `SmallBox<dyn Error,usize>` that exists without without std or alloc, provided your `Error` trait avoids std too.

---

_[View the full topic](https://internals.rust-lang.org/t/idea-fixed-sized-traits/12179)._
