Created
July 8, 2024 12:38
-
-
Save storopoli/8cf5a80c59a5aa26d3182debaa50c71b to your computer and use it in GitHub Desktop.
Rust: Object Safe Traits
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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