TIL: auto struct members

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Oct 18 21:36:31 PDT 2016


On Wednesday, October 19, 2016 03:30:06 Basile B. via Digitalmars-d-learn 
wrote:
> On Tuesday, 18 October 2016 at 22:12:47 UTC, Ali Çehreli wrote:
> > It may be embarrassing to discover this fact so late but you
> > can define struct members as 'auto':
> >
> > import std.range;
> > import std.algorithm;
> >
> > struct S {
> >
> >     auto r = only("a", "b").cycle;    // <-- WOW!
> >
> > }
> >
> > pragma(msg, typeof(S.r));
> >
> > /* Prints:
> >  *     Cycle!(OnlyResult!(string, 2LU))
> >  */
> >
> > // It's extra cool that S and the whole construct is @nogc pure
> > nothrow
> > // (In that regard, only() is better than an array as the
> > latter cannot
> > // be @nogc. i.e. [ "a", "b", "a" ] cannot be @nogc.)
> > void foo() @nogc pure nothrow {
> >
> >     assert(S().r.take(3).equal(only("a", "b", "a")));
> >
> > }
> >
> > void main() {
> > }
> >
> > Ali
> >
> > P.S. I propose a new attribute, @cool, which should mean '@nogc
> > pure nothrow'. :o)
>
> It also works if it's an enum, but without surprise because this
> kind of enums are grammatically the same as an auto declaration.

In D, all auto is is a placeholder for a type in a variable declaration.
Type inference actually _always_ happens unless you provide the exact type.
So, stuff like enum, const, immutable, static, etc. all are enough without
needing auto. It's just that if you don't want any of those other
attributes, you need the auto to indicate that you're defining a variable.

I expect that the reason that Ali was surprised is that even if you're used
to using auto all over the place in functions, you probably think of a
user-defined type having fields of specific types, and you often don't
directly initialize a member variable, in which case, you need the type.
So, it can be easy to not realize that auto works with member variables too
simply because you never thought about it.

- Jonathan M Davis




More information about the Digitalmars-d-learn mailing list