Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What safety guarantees of Rust would be lost if not for object safety?

Tags:

rust

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?

like image 208
sgldiv Avatar asked Jan 06 '23 17:01

sgldiv


1 Answers

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.

like image 139
Shepmaster Avatar answered Jan 15 '23 02:01

Shepmaster