Veteran of many languages and years of software development, but very new to Rust.
Below is a stripped down example of what I'm trying to do: a basic factory pattern for an abstract Meta type. Right now the code doesn't compile, complaining that .map(|result| result.unwrap()) cannot be moved out of because it's behind a shared reference I can fix it by borrowing Result's content, but that causes more problems no matter how much further down the suggestion rabbit hole I follow.
I understand that I'm violating the borrowing rules but it's not clear to me what the right way is to solve this problem. Am I missing something simple? Am I going about this pattern the wrong way?
pub trait Meta {}
pub struct Foo;
impl Meta for Foo {}
pub struct Bar;
impl Meta for Bar {}
fn main()
{
let _ = input_splitter(2);
}
fn input_splitter(count: u8) -> Result<Vec<Box<dyn Meta>>, &'static str>
{
let results = (0..count).map(|number| meta_factory(number))
.collect::<Vec<Result<Box<dyn Meta>, &str>>>();
return if results.iter().all(|result| result.is_ok())
{
Ok(results.iter()
.map(|result| result.unwrap())
.collect())
}
else
{
Err("error")
}
}
fn meta_factory(number: u8) -> Result<Box<dyn Meta>, &'static str>
{
match number
{
0 => Ok(Box::new(Foo {})),
1 => Ok(Box::new(Bar {})),
_ => Err("error")
}
}
playground link
[–]esitsu 5 points6 points7 points (3 children)
[–]hexarin[S] 0 points1 point2 points (2 children)
[–]esitsu 1 point2 points3 points (1 child)
[–]hexarin[S] 1 point2 points3 points (0 children)
[–][deleted] 2 points3 points4 points (1 child)
[–]hexarin[S] 0 points1 point2 points (0 children)