4

I am trying to understand the idea of being object safe. I know from the documentation that object safety is that following hold:

  • The trait does not require that Self: Sized
  • All of its methods are object-safe

What things that conceivably could lead to the failure of the safety guarantees that safe Rust makes can be accomplished if either one of the two conditions required for object safety are dropped?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
sgldiv
  • 623
  • 6
  • 16
  • Have you read [*Object Safety*](http://huonw.github.io/blog/2015/01/object-safety/) and [*Where Self Meets Sized: Revisiting Object Safety*](http://huonw.github.io/blog/2015/05/where-self-meets-sized-revisiting-object-safety/) by Huon Wilson? – Shepmaster Jul 12 '16 at 01:51
  • Yes... "where the internals make it impossible to actually use with trait objects." - I inferred that as meaning type signatures may be satisfied, but may run afoul of borrow checking or lifetimes (??) -so you cannot use it. The two conditions are sufficient to get it to actually compile. But are they necessary? It would be good to see examples where dropping either would get you into trouble, and what exactly obstructs. – sgldiv Jul 12 '16 at 02:33

1 Answers1

9

From Where Self Meets Sized: Revisiting Object Safety:

A trait is object safe only if the compiler can automatically implement it for itself, by implementing each method as a dynamic function call through the vtable stored in a trait object.

Without the object safety rules one can write functions with type signatures satisfied by trait objects, where the internals make it impossible to actually use with trait objects.

I believe that the choice of phrasing of "object safety" may be a poor one in retrospect as it doesn't appear to have anything to do with memory safety, the normal use of the term "(un)safe" in Rust.

Object "ability" may be closer to the truth; a trait that has the ability to be referred to via a trait object.

Community
  • 1
  • 1
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 1
    To clarify, the problem isn't that giving the ability to use these as trait objects is dangerous, but that you just can't implement it that way. – Veedrac Jul 12 '16 at 04:44
  • +1 for the weird use of "safety" here, the problem is not about safety, it's about not being able to implement a virtual dispatch. – Matthieu M. Jul 12 '16 at 07:27
  • 1
    I think it would be helpful to have an example of where this would go wrong here. – Chris Emerson Jul 12 '16 at 10:51