前两天遇到一个题,求指导
代码已经附上 playground,求答案
Ext Link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&code=%23%21%5Ballow%28dead_code%29%5D%0D%0A%23%21%5Ballow%28unused_imports%29%5D%0D%0Ause+std%3A%3Amarker%3A%3APhantomData%3B%0D%0A%23%5Bcfg%28feature+%3D+%22check%22%29%5D%0D%0Afn+gen_afunc%3CT%3A+Trait%3E%28%29+-%3E+impl+AFunc%3CT%3E%7B%0D%0A++++todo%21%28%29%0D%0A%7D%0D%0A%0D%0A%0D%0A%23%5Bcfg%28feature+%3D+%22check%22%29%5D%0D%0Afn+gen_bfunc%3CT%3A+Trait%3E%28%29+-%3E+impl+BFunc%3CTy+%3D+T%3E+%7B%0D%0A++++todo%21%28%29%0D%0A%7D%0D%0A%0D%0A%0D%0A%0D%0Afn+main%28%29+%7B%0D%0A++++%23%5Bcfg%28feature+%3D+%22check%22%29%5D+%0D%0A++++%7B%0D%0A++++++++fn+generic%3CT%3A+Trait%3E%28%29+%7B%0D%0A++++++++++++c_func1%3A%3A%3CT%3E%28gen_afunc%28%29%29%3B%0D%0A++++++++++++c_func2%3A%3A%3CT%3E%28gen_bfunc%28%29%29%3B%0D%0A++++++++++++d_func1%3A%3A%3CT%3E%28gen_afunc%28%29%29%3B%0D%0A++++++++++++d_func2%3A%3A%3CT%3E%28gen_cfunc%28%29%29%3B%0D%0A++++++++%7D%0D%0A++++++++generic%3A%3A%3Ci32%3E%28%29%3B%0D%0A++++++++generic%3A%3A%3Ci64%3E%28%29%3B%0D%0A++++%7D%0D%0A++++println%21%28%22execute+%60cargo+run+--features%3Dcheck%60+if+you+have+completed%22%29%0D%0A%7D%0D%0Atrait+Trait%3A+Default+%7B%7D%0D%0Aimpl%3CT%3A+Default%3E+Trait+for+T+%7B%7D%0D%0Atrait+AFunc%3CT%3E%7B%0D%0A++++fn+call%28%26self%29+-%3E+T%3B%0D%0A%7D%0D%0A%0D%0Atrait+BFunc%7B%0D%0A++++type+Ty%3B%0D%0A++++fn+call%28%26self%29+-%3E+Self%3A%3ATy%3B%0D%0A%7D%0D%0A%0D%0Afn+c_func1%3CT%3ATrait%3E%28imp%3Aimpl+AFunc%3CT%3E%29+-%3E+T%7B%0D%0A++++imp.call%28%29%0D%0A%7D%0D%0A%0D%0Afn+c_func2%3CT%3ATrait%3E%28imp%3Aimpl+BFunc%3CTy+%3D+T%3E%29+-%3E+T%7B%0D%0A++++imp.call%28%29%0D%0A%7D%0D%0A%0D%0Afn+d_func1%3CT%3ATrait%3E%28imp%3Aimpl+AFunc%3CT%3E%29+-%3E+impl+Trait+%7B%0D%0A++++imp.call%28%29%0D%0A%7D%0D%0A%0D%0Afn+d_func2%3CT%3ATrait%3E%28imp%3Aimpl+BFunc%3CTy+%3D+T%3E%29+-%3E+impl+Trait+%7B%0D%0A++++imp.call%28%29%0D%0A%7D
1
共 2 条评论, 1 页
评论区
写评论大哥,感谢您!
--
👇
Bai-Jinlin: ```rust use std::marker::PhantomData;
impl<T: Trait> AFunc for PhantomData { fn call(&self) -> T { T::default() } } impl<T: Trait> BFunc for PhantomData { type Ty = T;
} fn gen_afunc<T: Trait>() -> impl AFunc { PhantomData }
fn gen_bfunc<T: Trait>() -> impl BFunc<Ty = T> { PhantomData }
fn gen_cfunc<T: Trait>() -> impl BFunc<Ty = T> { PhantomData }
fn main() { { fn generic<T: Trait>() { c_func1::(gen_afunc()); c_func2::(gen_bfunc()); d_func1::(gen_afunc()); d_func2::(gen_cfunc()); } generic::(); generic::(); } } trait Trait: Default {} impl<T: Default> Trait for T {} trait AFunc { fn call(&self) -> T; }
trait BFunc { type Ty; fn call(&self) -> Self::Ty; }
fn c_func1<T: Trait>(imp: impl AFunc) -> T { imp.call() }
fn c_func2<T: Trait>(imp: impl BFunc<Ty = T>) -> T { imp.call() }
fn d_func1<T: Trait>(imp: impl AFunc) -> impl Trait { imp.call() }
fn d_func2<T: Trait>(imp: impl BFunc<Ty = T>) -> impl Trait { imp.call() }