Skip to content

Instantly share code, notes, and snippets.

@ccqpein
Created December 30, 2018 15:58
Show Gist options
  • Save ccqpein/05d503a3f231bf4c6d1dcca48dac762c to your computer and use it in GitHub Desktop.
Save ccqpein/05d503a3f231bf4c6d1dcca48dac762c to your computer and use it in GitHub Desktop.
Rust return different structs those implement same trait
struct Test0;
struct Test1;
trait A {}
impl A for Test0 {}
impl A for Test1 {}
//failed
/*fn test(a: i32) -> impl A {
if a < 1 {
return Test0;
}
return Test1;
}*/
//all below works
fn test1(a: i32) -> Box<dyn A> {
if a < 1 {
return Box::new(Test0);
}
return Box::new(Test1);
}
fn test2(a: i32) -> impl A {
return Test1;
}
fn test3(a: i32) -> Box<A> {
if a < 1 {
return Box::new(Test0);
}
return Box::new(Test1);
}
fn main() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment