Skip to content

Instantly share code, notes, and snippets.

@greglearns
Forked from sciolizer/inference.rs
Created November 12, 2022 00:56
Show Gist options
  • Save greglearns/faa32f541c981b2ad571178e852518b1 to your computer and use it in GitHub Desktop.
Save greglearns/faa32f541c981b2ad571178e852518b1 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