A struct member function that transforms the struct into another struct. Is this a good pattern?

⚓ Rust    📅 2026-03-12    👤 surdeus    👁️ 5      

surdeus

I have a trait that implements a builder for struct Foo. The builder type has a field, which is a function, that transforms itself to Foo. I was wondering if this a good pattern and if there are any reasons for not doing this.

#[derive(Default)]
struct Foo {}

trait FooBuilder {
    fn build(self) -> Foo;
}

struct FooBuilderType {
    transform: fn(Self) -> Foo,
}

impl FooBuilder for FooBuilderType {
    fn build(self) -> Foo {
        (self.transform)(self)
    }
}

impl Default for FooBuilderType {
    fn default() -> Self {
        Self {
            transform: |_| Foo::default(),
        }
    }
}

impl FooBuilderType {
    fn new() -> Self {
        Self::default()
    }

    fn with_transform(mut self, f: fn(Self) -> Foo) -> Self {
        self.transform = f;
        self
    }
}

The main reason for my concern is that it is easy to cause a stack overflow by having the transformation be an infinite recursion and this does not get detected at compile time. Rust Playground

fn main() {
    let builder = FooBuilderType::new().with_transform(|x| (x.transform)(x));
    let _ = builder.build();
}

1 post - 1 participant

Read full topic

🏷️ Rust_feed