How can I check if an element is iterable?
Marcone
marcone at email.com
Mon May 4 11:29:40 UTC 2020
On Monday, 4 May 2020 at 01:49:28 UTC, Ali Çehreli wrote:
> On 5/3/20 1:44 PM, Marcone wrote:
>> [...]
>
> Still, the type of a variable would determine whether whether
> it's iterable.
>
> As an improvement, the following program can be changed to call
> use() recursively to visit all members of e.g. structs (which
> can be determined by 'is (T == struct)').
>
> import std.stdio;
> import std.traits;
>
> void use(T)(T var, size_t indent = 0) {
> static if (isIterable!T && !isSomeString!T) {
> foreach (i, e; var) {
> writefln!"%*s: %s"(indent, i, e);
> }
>
> } else {
> writefln!"%*s"(indent, var);
> }
> }
>
> void main() {
> int i = 42;
> string s = "hello";
> double[] arr = [ 1.5, 2.5, 3.5 ];
> use(i);
> use(s);
> use(arr);
> }
>
> Ali
Very good! Thank you!
More information about the Digitalmars-d-learn
mailing list