auto keyword

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Jan 30 22:46:38 UTC 2020


On Thu, Jan 30, 2020 at 09:37:40AM +0000, Michael via Digitalmars-d-learn wrote:
[...]
> auto elements = buf.to!string.strip.split(" ").filter!(a => a != "");
> 
> That line strips white space from buf, splits it, removes empty
> elements and returns an array of strings. At least I thought so.

If you want an array of strings, just add .array to the end, and you
will get string[] back.


> Indeed elements can be treated as a string slice, but if i replace
> auto by string[] the compiler complains:
> Error: cannot implicitly convert expression filter(split(strip(to(buf)), "
> ")) of type FilterResult!(__lambda1, string[]) to string[]

That's because the actual type is a lazily-evaluated range.


> In order to use an explicit type I wonder what kind of type I might
> use instead of auto?

In this case, you actually can't spell out the type, because it's a
Voldemort type (it's only defined inside the function that constructs
it, and is not directly nameable outside).  Usually, a Voldemort type is
returned when you *shouldn't* be referring to it with an explicit type.
For example, in this case, if what you really want is an array of
strings then you should add .array at the end to get a string[].

If you wish to store the lazy range, for whatever reason, you can use
the typeof() operator to extract a type from it (without actually
spelling it out -- because you can't):

	auto elements = buf.to!string.strip.split(" ").filter!(a => a != "");
	alias E = typeof(elements);
	E x;
	x = elements;

Usually this is only useful if you wish the store the lazy range inside
some kind of aggregate type while retaining its lazy evaluation
semantics.  But if you expect it to be eagerly evaluated anyway, there's
no need to jump through hoops to get at the type of `elements`; just
stick .array to the end of it and get a string[] back.


T

-- 
"The whole problem with the world is that fools and fanatics are always so certain of themselves, but wiser people so full of doubts." -- Bertrand Russell. "How come he didn't put 'I think' at the end of it?" -- Anonymous


More information about the Digitalmars-d-learn mailing list