Skip to content

Instantly share code, notes, and snippets.

@storopoli
Created July 8, 2024 12:38
Show Gist options
  • Save storopoli/8cf5a80c59a5aa26d3182debaa50c71b to your computer and use it in GitHub Desktop.
Save storopoli/8cf5a80c59a5aa26d3182debaa50c71b to your computer and use it in GitHub Desktop.
Rust: Object Safe Traits
// In general there are two properties for traits to satisfy
// in order them to be object-safe:
//
// 1. The return type isn’t Self.
// 2. There are no generic type parameters.
// Here's an example of a non-object-safe Trait
trait MyTrait {
fn f(&self) -> Self;
}
impl MyTrait for u32 {
fn f(&self) -> Self { 42 }
}
impl MyTrait for String {
fn f(&self) -> Self { self.clone() }
}
// What should this function return?
fn my_function(x: Box<dyn MyTrait>) -> ??? {
x.f()
}
fn main() {
my_function(Box::new(13_u32));
my_function(Box::new(String::from("abc")));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment