Conventions for naming mutable / immutable API functions?

When writing APIs, it usually has a mutable and immutable version of the method.

I expected the standard library to have clear conventions on how to name them, but it doesn’t fully comply with 1 :

What are the good naming conventions for the following methods?

pub fn foo****(&self) -> &Bar { ... }
pub fn foo****(&mut self) -> &mut Bar { ... }
  • foo() | foo_mut()

    This seems the most common, and it can be seen in Vec.iterand Vec.iter_mut.

  • foo_ref() | foo_mut()

    Used for Any.downcast_refand Any.downcast_mut.

The first case seems to be more common, so what are the reasons for using the suffix _refwhen starting the naming of API functions?


1 . This is probably consistent, and I just don't notice the reasoning.

+4
1

, RFC 199. :

foo / , :

  • _mut (, foo_mut) .
  • _move (, foo_move) .

into, into_iter for x in v.into_iter() , , , for x in v.iter_move(), into_iter.

. , . RFC.

foo / , :

  • _ref (, foo_ref) .
  • _mut (, foo_mut) .

Any::downcast_ref downcast, downcast Box<Any + 'static> Box<Any + 'static + Send>, self . Any downcast , . , :

+7

Source: https://habr.com/ru/post/1668567/


All Articles