How about Go's &Struct instead of new?

Justin Johansson no at spam.com
Thu Nov 12 12:48:12 PST 2009


Bill Baxter Wrote:

> I fear there could be a long parade of these "How about Go's ____"
> topics, but anyway, here goes...
> ....
> Mostly just a syntax bikeshed, but this seemed like a nice way to
> eliminate the "new" syntax that wasn't mentioned previously.
> They also kind of round out the declaration possibilities so that all
> these built-ins can be declared as auto or as literals. For instance,
> a function that needs a 10 element scratch array passed in could be
> called like:
>        foo(A,B, float[10][]);
> equivalent to
>        float[10] tmp;
>        foo(A,B, tmp[]);


'... but this seemed like a nice way to eliminate the "new" syntax that
wasn't mentioned previously.'

Somewhat related to this post ...

Currently in my D projects I use static opCall to eliminate "new" (at least for
classes) such as:

class Foo
{
  int x;
  Foo( int x) { this.x = x; }
  static Foo opCall( int x) { return new Foo( x); }
}

I'm not sure if this considered good D style of not (please advise), but it does
eliminate having to type new all the time to allocate and construct new Foo's.

However, for consistency, I find myself often typing in static opCall boiler-plate code 
when creating a new class definition even for classes which few instances are
ever created in the wild.  In some cases, then, more overall keystrokes are
incurred just to save the infrequent new keyword when instantiating the class.

Analysing the break-even point (minimum number of new's to save) for the
static opCall keystroke overhead is (at least in this case) .. hmm .. let's see ...

"new" is 3 characters but at least one whitespace separator is needed so that
makes 4 characters "new ".

Now the following comparison text (edited in fixed-width font, 1st line is 50 chars; 2nd is 48):

static Foo opCall( int x) { return new Foo( x); }
new new new new new new new new new new new new

Whilst I like the idea of getting rid of new keyword, I must admit that on the
balance I generally don't save any keystrokes using the static opCall instrument.

btw.  My thinking for getting rid of new keyword came from some experience
with Scala case classes and companion classes (Object in Scala parlance).
>From what I understand/remember, "Object" is Scala's way of getting rid of "static" in
relation to class member variables and methods.  In some ways, D opCall some analogy
with these Scala idioms.

What do others think?

Justin Johansson






More information about the Digitalmars-d mailing list