What to choose: self->Self or &mut self->&mut Self


#1
struct A;

impl A {
    fn then_owned(self, _: i32) -> Self {
        self
    }

    fn then_mut(&mut self, _: i32) -> &mut Self {
        self
    }
}

fn pass_a(_: A) {}

fn main() {
    {
        pass_a(A.then_owned(0)
                .then_owned(1)
                .then_owned(2));
    }
    {
        let mut a = A;
        a.then_mut(0)
         .then_mut(1)
         .then_mut(2);
        pass_a(a);
    }
}

What is faster? What is better? And why?


#2

I would prefer the mutable solution as it enables people (for various reasons useful) to call every method on one instance, if none of the below reasons seem applicable.

e.g.:

a.then_mut(x);
b.then_mut(x);

a.then_mut(y);
b.then_mut(y);

However, these kind of pattern, the builder pattern, should be uniform, meaning it should be the same pattern for all methods.
This could limit your ability to introduce new features later.

You could for example decide to have a method that could Err. (fn something(self,_: i32) -> Result<Self,SomeError>)
In this case you have the two options, &mut or owned.
It is now depending on whether you like to consume the value in case of an Err or leave it up to the user to retry or use the half-built structure otherwise.

You could also decide to introduce a method returning a different type that owns the passed one.
It would be good if you’d choosen to use the owned version then, as again, every function signature should use the same pattern.