Skip to content

Instantly share code, notes, and snippets.

@appcypher
Last active November 16, 2021 08:01
Show Gist options
  • Save appcypher/fc36ed112964f46534bfbb52b1a793cd to your computer and use it in GitHub Desktop.
Save appcypher/fc36ed112964f46534bfbb52b1a793cd to your computer and use it in GitHub Desktop.
Conversion Bewteen &impl Trait and &dyn Trait
trait Fmt {}
// This allows conversion from ?Sized like `&dyn Fmt` back to `&impl Fmt`
impl Fmt for &dyn Fmt {}
struct FmtStruct();
impl Fmt for FmtStruct {}
fn expects_dyn(fmt: &dyn Fmt) -> &dyn Fmt {
fmt
}
fn expects_impl(fmt: &impl Fmt) -> &impl Fmt {
fmt
}
fn test_conversions<F: Fmt>(fmt: &F) {
// &impl Fmt easily becomes &dyn Fmt.
let ref_dyn_fmt: &dyn Fmt = expects_dyn(fmt);
// &dyn Fmt can only become &impl Fmt here because we implemented `Fmt for &impl Fmt + ?Sized`,
// which is usually &dyn Fmt. We could have also implemnted `Fmt for &dyn Fmt` but that is not
// general to all ?Sized.
let _ref_impl_fmt = expects_impl(&ref_dyn_fmt); // Has type &impl Fmt.
}
fn main() {
let fmt_struct = FmtStruct();
test_conversions(&fmt_struct);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment