On 5/3/20 1:44 PM, Marcone wrote:
On Sunday, 3 May 2020 at 20:11:58 UTC, Adam D. Ruppe wrote:
On Sunday, 3 May 2020 at 20:02:09 UTC, Marcone wrote:
How can I check if an element is iterable in Dlang?

http://dpldocs.info/experimental-docs/std.traits.isIterable.html

I don't want to check if type is iterable, but if variable is iterable.

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

Reply via email to