Skip to content

Instantly share code, notes, and snippets.

@sciolizer
Last active November 12, 2022 00:56
Show Gist options
  • Save sciolizer/fe22691d4109b4376187fce1f1cad236 to your computer and use it in GitHub Desktop.
Save sciolizer/fe22691d4109b4376187fce1f1cad236 to your computer and use it in GitHub Desktop.
Rust inference feeling somewhat arbitrary
trait MyTrait {}
struct MyStruct;
impl MyTrait for MyStruct {}
fn compiles1() -> Box<dyn MyTrait> {
Box::new(MyStruct)
}
fn compiles2() -> Box<dyn MyTrait> {
let value = Box::new(MyStruct);
value
}
struct MyWrapper<A>(A);
fn compiles3() -> MyWrapper<Box<dyn MyTrait>> {
MyWrapper(Box::new(MyStruct))
}
fn does_not_compile() -> MyWrapper<Box<dyn MyTrait>> {
let value = MyWrapper(Box::new(MyStruct));
value
}
// after talking to the discord channel:
impl<T, U> CoerceUnsized<MyWrapper<U>> for MyWrapper<T> where T: CoerceUnsized<U> {}
fn now_it_compiles() -> MyWrapper<Box<dyn MyTrait>> {
let value = MyWrapper(Box::new(MyStruct));
value
}
// though this is not a good solution in practice, it's interesting
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment