mutable/immutable API 函数的命名约定?

Conventions for naming mutable/immutable API functions?

编写 API 时,方法的可变版本和不可变版本很常见。

我希望标准库对如何命名这些有明确的约定,但并不完全一致1:

以下方法的良好命名约定是什么?

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

似乎第一种情况比较常见,那么在命名API函数时使用_ref后缀的原因是什么?


1: 大概是一致的,我只是没有注意到推理。

是的,RFC 199 中定义了此约定。重要的部分是:

The rules

Immutably borrowed by default

If foo uses/produces an immutable borrow by default, use:

  • The _mut suffix (e.g. foo_mut) for the mutably borrowed variant.
  • The _move suffix (e.g. foo_move) for the owned variant.

However, in the case of iterators, the moving variant can also be understood as an into conversion, into_iter, and for x in v.into_iter() reads arguably better than for x in v.iter_move(), so the convention is into_iter.

NOTE: This convention covers only the method names for iterators, not the names of the iterator types. That will be the subject of a follow up RFC.

Owned by default

If foo uses/produces owned data by default, use:

  • The _ref suffix (e.g. foo_ref) for the immutably borrowed variant.
  • The _mut suffix (e.g. foo_mut) for the mutably borrowed variant.

Any::downcast_ref 不被称为 downcast,因为 Box<Any + 'static> and on Box<Any + 'static + Send> 上有一个名为 downcast 的方法,它按值获取 self。将方法命名为 Any downcast 会导致一个遮蔽另一个。所以整个画面是: