Going to try returning impl trait before resorting to boxing

This commit is contained in:
Tom Alexander 2020-04-11 21:44:42 -04:00
parent 43e57f4134
commit 110b03fc45
Signed by: talexander
GPG Key ID: D3A179C9A53C0EDE
2 changed files with 21 additions and 7 deletions

View File

@ -118,6 +118,10 @@ mod tests {
fn walk(&self, segment: &str) -> &I { fn walk(&self, segment: &str) -> &I {
self.get(segment).unwrap() self.get(segment).unwrap()
} }
fn val(&self) -> String {
"val".to_owned()
}
} }
impl<'a> Walkable for &str { impl<'a> Walkable for &str {
@ -126,6 +130,10 @@ mod tests {
fn walk(&self, segment: &str) -> &u32 { fn walk(&self, segment: &str) -> &u32 {
panic!("Tried to walk down a str"); panic!("Tried to walk down a str");
} }
fn val(&self) -> String {
"val".to_owned()
}
} }
impl<'a> Walkable for u32 { impl<'a> Walkable for u32 {
@ -134,12 +142,16 @@ mod tests {
fn walk(&self, segment: &str) -> &u32 { fn walk(&self, segment: &str) -> &u32 {
panic!("Tried to walk down a str"); panic!("Tried to walk down a str");
} }
fn val(&self) -> String {
"val".to_owned()
}
} }
fn do_the_walk<'a, O: Walkable>( fn do_the_walk<'a, O: Walkable>(
context: &'a dyn Walkable<Output = O>, context: &'a dyn Walkable<Output = O>,
path: &Vec<&str>, path: &Vec<&str>,
) -> &'a O { ) -> &'a impl Walkable {
let mut output = context; let mut output = context;
context.walk(path.first().unwrap()) context.walk(path.first().unwrap())
@ -170,11 +182,11 @@ mod tests {
.iter() .iter()
.cloned() .cloned()
.collect(); .collect();
assert_eq!(do_the_walk(&context, &vec!["cat"]), &"kitty"); assert_eq!(do_the_walk(&context, &vec!["cat"]).val(), "kitty");
assert_eq!(do_the_walk(&number_context, &vec!["tiger"]), &3); // assert_eq!(do_the_walk(&number_context, &vec!["tiger"]), &3);
assert_eq!( // assert_eq!(
do_the_walk(&deep_context, &vec!["tiger"]), // do_the_walk(&deep_context, &vec!["tiger"]),
&[("food", "people")].iter().cloned().collect() // &[("food", "people")].iter().cloned().collect()
); // );
} }
} }

View File

@ -4,4 +4,6 @@ pub trait Walkable {
type Output: ?Sized + Walkable; type Output: ?Sized + Walkable;
fn walk(&self, segment: &str) -> &Self::Output; fn walk(&self, segment: &str) -> &Self::Output;
fn val(&self) -> String;
} }