Hi,
I'm trying to reduce the need for builder steps. Currently the user has to provide al mandatory elements (even though in the builder they are optional of course).
let permutate = Permutate::builder()
.with_genotype(genotype)
.with_reporter(PermutateReporterNoop::new())
.build()
.unwrap();
But I would like the PermutateReporterNoop (which implements the R trait below) to be a default (there are others so it adds up), so you can skip it:
let permutate = Permutate::builder()
.with_genotype(genotype)
.build()
.unwrap();
But I'm not able to do this. What am I not understanding here?
The struct and builder are below (stripped down to essence):
pub struct Permutate<
G: PermutableGenotype,
R: PermutateReporter<Genotype = G>,
> {
genotype: G,
reporter: R,
}
impl<G: PermutableGenotype, R: PermutateReporter<Genotype = G>>
TryFrom<PermutateBuilder<G, R>> for Permutate<G, R>
{
type Error = TryFromPermutateBuilderError;
fn try_from(builder: PermutateBuilder<G, R>) -> Result<Self, Self::Error> {
if builder.genotype.is_none() {
Err(TryFromPermutateBuilderError(
"Permutate requires a Genotype",
))
} else if builder.reporter.is_none() {
Err(TryFromPermutateBuilderError(
"Permutate requires a Reporter",
))
} else {
Ok(Self {
genotype: builder.genotype.unwrap(),
reporter: builder.reporter.unwrap(),
})
}
}
}
pub struct Builder<
G: PermutableGenotype,
R: PermutateReporter<Genotype = G>,
> {
pub genotype: Option<G>,
pub reporter: Option<R>,
}
impl<G: PermutableGenotype, R: PermutateReporter<Genotype = G>>
Builder<G, R>
{
pub fn new() -> Self {
Self::default()
}
pub fn build(self) -> Result<Permutate<G, R>, TryFromBuilderError> {
self.try_into()
}
pub fn with_genotype(mut self, genotype: G) -> Self {
self.genotype = Some(genotype);
self
}
pub fn with_reporter(mut self, reporter: R) -> Self {
self.reporter = Some(reporter);
self
}
}
impl<G: PermutableGenotype, R: PermutateReporter<Genotype = G>> Default
for Builder<G, R>
{
fn default() -> Self {
Self {
genotype: None,
reporter: None,
// reporter: Some(PermutateReporterNoop::new()),
// reporter: Some(R::default()),
}
}
}
extracted from GitHub - basvanwesting/genetic-algorithm: A genetic algorithm implementation for Rust