3

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?

  • If you don't specify a concrete type for T or F, then how much space should the Rust compiler allocate to store Struct? – Shepmaster May 18 '16 at 22:17
  • 1
    @Shepmaster, in theory, if the compiler can determine that F is 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
  • @Jsor an interesting point, but as you mention, Rust doesn't do any inference beyond a single function boundary. – Shepmaster May 18 '16 at 23:51
  • 1
    @Shepmaster can you elaborate or give some references about the affirmation "Rust doesn't do any inference beyond a single function boundary"? – malbarbo May 19 '16 at 11:37
2

Following Francis Gagné's clever solution, here's a similar idea that can work on stable Rust:

struct Struct<T, F: Fn(T)> {
    func: Option<F>,
    value: T,
}

enum Structs<T, F: Fn(T)> {
    Struct1(T),
    Struct2(T, F),
}

impl<T> Struct<T, fn(T)> {
    fn new(value: T) -> Struct<T, fn(T)> {
        Struct {
            func: None,
            value: value,
        }
    }
}

impl<T, F: Fn(T)> Struct<T, F> {
    fn func<F2: Fn(T)>(self, func: F2) -> Struct<T, F2> {
        Struct {
            func: Some(func),
            value: self.value,
        }
    }

    fn build(self) -> Structs<T, F> {
        use Structs::*;

        if let Some(func) = self.func {
            Struct2(self.value, func)
        } else {
            Struct1(self.value)
        }
    }
}

fn main() {
    let _strct = Struct::new(42)
        .func(|n| {
            println!("{}", n);
        })
        .build();

    let _strct = Struct::new(42).build();
}

Instead of a clear Void type, we simply say that we return a struct that would be parameterized for a function pointer. You could likewise specify a reference trait object:

impl<T> Struct<T, &'static Fn(T)> {
    fn new(value: T) -> Struct<T, &'static Fn(T)> {

Answering my own question from a comment:

If you don't specify a concrete type for T or F, then how much space should the Rust compiler allocate to store Struct?

The size of a fn() is 8 bytes on a 64-bit machine, leading to a total of 16 bytes for the entire structure:

std::mem::size_of::<fn()>();
std::mem::size_of_val(&strct);

However, when you give it a concrete callback, the structure only takes 8 bytes! That's because the type will be monomorphized for the callback, which needs no state and can basically be inlined.

Francis Gagné's solution only requires 8 bytes in each case, as the Void type has a size of zero!

  • 1
    In theory, a Struct<T, Void> could be even further optimized: since the Some variant of an Option<Void> cannot be instantiated, only the None variant remains. An enum with a single variant doesn't need a discriminant (though right now, it appears that there's still a discriminant for a unit enum), and since None doesn't hold any data, then the size of an Option<Void> could be zero. Thus, the size of a Struct<i32, Void> would be 4 rather than 8. – Francis Gagné May 19 '16 at 21:08
5

There's a way to solve this by changing the type of the builder as it evolves. Since Struct::func takes ownership of the builder and returns a new builder, we are free to change the result type.

First, we need to specify an initial type for F. We could just choose any existing implementation for Fn(T), but we can do better. I propose that we use an empty/void/uninhabited/bottom type, so that it's clear that when F is that type, then the Option is None (you can't construct a Some(x) because there's no valid x for an empty type). One downside to this approach is that implementing Fn, FnMut and FnOnce for types (other than closures) is unstable and requires a nightly compiler.

#![feature(fn_traits)]
#![feature(unboxed_closures)]

enum Void {}

impl<T> FnOnce<T> for Void {
    type Output = ();

    extern "rust-call" fn call_once(self, _args: T) {
        match self {}
    }
}

impl<T> FnMut<T> for Void {
    extern "rust-call" fn call_mut(&mut self, _args: T) {
        match *self {}
    }
}

impl<T> Fn<T> for Void {
    extern "rust-call" fn call(&self, _args: T) {
        match *self {}
    }
}

Next, let's move Struct::new to a different impl block:

impl<T> Struct<T, Void> {
    fn new(value: T) -> Struct<T, Void> {
        Struct {
            func: None,
            value: value,
        }
    }
}

This impl is not generic on F: new will only ever generate a Struct where F = Void. This avoids ambiguities in the case where func is never called.

Finally, we need to make func change the type of the builder:

impl<T, F0: Fn(T)> Struct<T, F0> {
    fn func<F1: Fn(T)>(self, func: F1) -> Struct<T, F1> {
        Struct {
            func: Some(func),
            value: self.value,
        }
    }
}

This method needs to stay in an impl block that is generic over the F type parameter on Struct<T, F>, so that it can be used on a builder on which func was already called. However, func must also be generic itself so that it can receive any type of function (rather than a function matching the type of the builder). Then, instead of mutating self, we have to construct a new Struct, because we can't just coerce a Struct<T, F0> into a Struct<T, F1>.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.