I have a struct that we can construct with the builder pattern because there are some Optional fields.
If I use the builder functions to specify these optional fields, I don't have to specify the generic parameters.
But if I don't call these functions, I need to specify the generic parameters.
Here is an example:
use Structs::*;
struct Struct<T, F: Fn(T)> {
func: Option<F>,
value: T,
}
enum Structs<T, F: Fn(T)> {
Struct1(T),
Struct2(T, F),
}
impl<T, F: Fn(T)> Struct<T, F> {
fn new(value: T) -> Struct<T, F> {
Struct {
func: None,
value: value,
}
}
fn build(self) -> Structs<T, F> {
if let Some(func) = self.func {
Struct2(self.value, func)
}
else {
Struct1(self.value)
}
}
fn func(mut self, func: F) -> Struct<T, F> {
self.func = Some(func);
self
}
}
fn main() {
let _strct = Struct::new(42)
.func(|n| { println!("{}", n); })
.build();
//let _strct = Struct::new(42).build(); // Does not compile.
let _strct = Struct::<_, &Fn(_)>::new(42).build();
}
I would like to omit the type annotation when the optional fields are not set, like so:
let _strct = Struct::new(42).build();
It should be specified that the F type depends on T.
I tried specifying a default type parameter as such:
impl<T, F: Fn(T) = Box<Fn(T)>> Struct<T, F> {
but it does not solve the issue.
So how can I avoid having to specify the type parameters in the Struct::new() call?
If it is not possible to avoid this, is there any alternatives to the builder pattern that would allow me to omit the type annotation?
TorF, then how much space should the Rust compiler allocate to storeStruct? – Shepmaster May 18 '16 at 22:17Fis never used it can just write that field as size 0. The problem, of course, is that this sort of whole-program inference is really complicated. – LinearZoetrope May 18 '16 at 23:48