Phobos examples and auto

Steven Schveighoffer schveiguy at yahoo.com
Mon Nov 7 04:17:59 PST 2011


On Sun, 06 Nov 2011 00:29:57 -0400, Steve Teale  
<steve.teale at britseyeview.com> wrote:

> On Sat, 05 Nov 2011 15:14:14 -0500, Andrei Alexandrescu wrote:
>
>>>> If we avoid "auto" in documentation examples but we do use it in
>>>> everyday code, we effectively foster a style that's foreign and
>>>> non-idiomatic to newcomers.
>
> Andrei,
>
> I don't use auto in everyday code, in fact I don't think I've ever used
> it at all. I've been with D for some years now, but apparently I write
> 'foreign and non-idiomatic' D. This goes just a tad beyond patronizing
> your reader.
>
> Can you write us a brief article that will convince me of its benefits,
> and the error of my ways please. There's no Borders where I live, and
> Amazon does not deliver to Africa, so I don't have the benefit of your
> book.

First, Borders is gone :)

http://online.wsj.com/article/SB10001424052702303661904576454353768550280.html

Second, auto is probably the best part of D besides slices.

The main reason auto is useful is it consolidates all type declarations  
into one location.

Take this (arguably arbitrary) pseudocode:

uint i = 5;
uint j = i;
uint k = j;
uint l = k;

If I want to make this code 64-bit aware, I need to change all 4 lines.   
If these lines are scattered throughout the code, I have to play the  
cyclical compiler game, where I change the first one, then compile, change  
the second one, compile, etc.

But compare to:

uint i = 5;
auto j = i;
auto k = j;
auto l = k;

I change one line, and it changes all the types throughout the code  
without me having to do *anything*.

If you step back and look at this from a concept level, the concept of  
auto (in this context) is saying "I want a copy of this value, I don't  
care what the type is".

That power is incredible for a statically typed language.  It almost  
rivals a dynamic typed one.

There is also the DRY T x = new T argument, but I think that's been  
well-covered.

Now, there's one more thing -- auto returns.  This I find to be necessary  
(for easy-to-write generic code), but in fact, *more* confusing than  
declaring the return type.  Simply because the user of your function has  
to do some testing of the introspection (i.e. pragma(msg,  
typeof(foo()).stringof) ), or must read the body of your function to  
figure out what's being returned (and that could depend on static ifs,  
more auto-return functions, etc.

If you look for my response to Andrei later I posted a couple days ago,  
I've outlined a solution which could be useful for allowing auto in  
examples, but giving more info for the interested reader.

-Steve


More information about the Digitalmars-d mailing list