Search code examples
rustnaming-conventionsnamingconventions

What is the conventional name for a method accepting a closure and providing temporal field access for it?


I have a Rust struct which can be simplified like this:

struct Struct {
    field: String // the type doesn't matter
}
impl Struct {
    pub fn method<F, R>(&self, closure: F) -> R
    where
        F: FnOnce(&String) -> R
    {
        closure(&self.field)
    }
}

Are there any conventional names for Struct::method (used in the Rust Book or the standard library in similar cases)? Is it expected to be apply, visit..?


Solution

  • If there is only one such method and the data it receives is central to Struct, I'd go with:

    • map() if it consumes/transforms Struct and returns a new Struct, as in Option::map()
    • with() if it receives a shared reference to the data, as in LocalKey::with()
    • with_mut() if the function receives a unique/mutable reference to the data. (I don't have a good reference for this one, but it's a logical extension of with(), and consistent with iter() and iter_mut() on containers.)

    If there are multiple such methods, or it's not obvious what subset of Struct's data it operates on, I'd call add the field name, as in with_field() or with_mut_field().