[rust-dev] Class UI

Niko Matsakis niko at alum.mit.edu
Thu Apr 12 11:54:50 PDT 2012

On 4/12/12 7:45 AM, Benjamin Striegel wrote:
> Optional named parameters in function invocations could be a third 
> option, although of course that introduces a third inflexibility to 
> consider. :P
> So, which happens most often?

I suppose it's not only a question of what happens most often, but what 
is most surprising. That is, if I change the order of fields, perhaps I 
am very surprised that code breaks, whereas if I change the names, less so?
> 1) You create a class without any constructor besides property 
> assignment, and then later introduce a more substantial constructor.

Personally speaking, the majority of my classes tend to have no "real" 
constructor happens a lot to me. I am not sure how often they migrate to 
a more substantial constructor. Probably infrequently.

> 2) You alter the order of fields/memory layout of a class.
> 3) You change the names of a class' fields.

Hard to say. However, I will add one other wrinkle: if I change the 
names of the fields, I get errors that are very clear and easy to 
correct. If I change the order of the fields, and the fields have the 
same type, I get no errors at all—until runtime, that is! This is bad.

(Incidentally, it's why I far prefer Smalltalk-style "match based on a 
label" style to the far more prevalent "parameter-list" style. But that 
ship, too, has sailed.)

So, therefore, I propose something like this. Class instances are 
*always* created by writing "C { f1: v1, ..., fN: vN }". A class can, 
however, declare "priv new" or something like that to indicate that the 
constructor is private to the class. We can then permit static functions 
(which are probably useful anyhow) that can serve as blessed constructors:

class C {
static fn create(...) -> C {
ret C { f1: v1, ..., fN: vN };

You would then create an instance of C using `C::create(...)`. The only 
thing I am not sure about is how one declares the construction to be 

Perhaps it's enough to say "if there are private fields, you must use a 
static function within the class to construct an instance". In any case 
we probably want such a rule (at least pcwalton feels strongly that it 
should exist).


More information about the Rust-dev mailing list