Naming convention for methods that modify vs methods that return new

Is there some naming convention that's used to identify whether a method is going to perform an in-place modification [edit: I guess by this I really just mean a mutation] as opposed to returning a new instance of the same type?

Obviously you can look at the type signature to get this information but I've seen other languages (such as Swift if I recall correctly) that have such a convention, and am wondering if Rust has any similar conventions.

Thanks!

I believe the convention is:

  • .set_foo(&mut self, Foo) for in-place mutation
  • .with_foo(self, Foo) -> Self for returning a new Self
  • .foo(&self, Foo) -> SelfBuilder when using the builder pattern

That is mostly for setting fields or individual attributes, in general there's no convention for methods taking &mut self vs self.

1 Like

I'm thinking no. For example, replace and replace_range: the former returns a new String and the latter modifies in-place. Looks like in Swift replace would be replaced, replacing, or replacement.

There isn't really anything going against Swift's convention, but I haven't seen any rules about this in particular.

1 Like

Thanks very much both!

@drewtato Yeah this seems to fit in with a few other examples I've seen in the standard library (and agreed re: Swift - and I very much like their approach here). I'll just have to be careful with my naming I think so that it tries to convey intent to calling code. Thank you!

I don't apply this entirely consistently, but when I need the distinction I tend to lean toward: future-tense verb ⇒ operating on value in-place, past-tense verb ⇒ return new value. e.g. mutate ⇒ in-place, mutated ⇒ new value.

2 Likes

Yeah I think this is what Swift does (it's been a while since I've worked with it), and it makes good sense to me. I'll probably adopt the same convention I think.

I have a feeling Ruby has a convention too, where mutating methods have a bang. This would obviously conflict with Rust's macro naming, but it's another example of what other languages do. Ah well!

Thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.