Which is better?

struct A;
impl<'this> A {
    pub fn new() -> Self {
        return Self;
    }

    pub fn do_a(&'this mut self) -> &'this mut Self {
        return self;
    }

    pub fn do_b(&'this self) -> bool {
        return true;
    }
}

Which way of writing code is better in Rust internal operations context?
This? a

let a: A = A::new();
a.do_a().do_b();

Or this? b

let a: A = A::new();
a.do_a();
a.do_b();

Both are fine. I don't think there's any consensus about which is better. There's a third option:

fn do_a(self) -> Self { self }

which is used for things like iterator chains. It's not better or worse than &mut self, they interact with ownership and borrowing differently.

BTW: you don't need <'this>. If you don't write any lifetime annotations, the default assumption is that returned references borrow from arguments, which is almost the same what you've written. Explicit lifetimes on &self generally are not needed, and can only cause problems.

2 Likes

Honestly it depends on what exactly you're doing.

3 Likes

To expand on what @kornel said, using

fn do_a(self) -> Self { self }

instead of your version of do_a() allows you to do

let a = A::new().do_a();
a.do_b();

Your version wouldn't work because it returns a reference to a temporary value.

2 Likes