Last active
November 16, 2021 08:01
-
-
Save appcypher/fc36ed112964f46534bfbb52b1a793cd to your computer and use it in GitHub Desktop.
Conversion Bewteen &impl Trait and &dyn Trait
This file contains hidden or 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
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