Skip to content

RFC: static methods in classes #2376

Closed
Closed
@catamorphism

Description

@catamorphism

When discussing #2290 with @nikomatsakis and @pcwalton , we agreed that static methods might potentially be useful in classes. One of the motivating cases is to simplify how constructors get treated. We could even eliminate class constructors altogether, and write something like:

class cat {

  let name: str;
  let meow_count: uint;

  /* Requires a self parameter */
  fn meow() { ... }

  /* Doesn't require a self parameter */
  static fn cat(name: str) -> cat {
     cat{ name: name, meow_count: 0u } 
  }

}

In this case, there's no constructor, but rather, a static method called cat that returns a new instance of the class cat. I'm also assuming that a version of record initialization syntax could be used for classes, which doesn't work right now, but could be made to work. Since classes are nominal, we would need to prefix the record literal with the class name; this would decouple whatever other computation a constructor needs to do from the act of actually allocating a new record and filling in the class fields.

So I'm proposing to:

  • add a static modifier on function items, only valid within a class declaration, whose semantics are that a function declared as static fn f... requires no self argument and cannot refer to self in its body -- however, f can refer to class-private fields in its enclosing class.
  • add syntax to call static methods in a class C with the C:: prefix: as in, cat::cat() above (This is up for discussion -- I don't care how the exact syntax looks)
  • allow a nominal version of record initialization syntax to be used to create class literals

Notice that this removes the need for @class (as in the original spec, #1726) because you can now write a static method that takes an explicit self parameter.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions