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

View File

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