Walter is showing the equivalent function declaration... you will eventually create a generic type as you say, but in the Zig example, that was a function, not a struct.
But I agree it probably returns a struct type.
Assuming that's the case, you're right and the equivalent would be:
Zig:
fn ArrayListType(comptime T: type) type {
D: ArrayList!T ArrayListType(T)() {
But now the D version is more specific about what it returns, so it's still not exactly equivalent.If you must return different types depending on the argument in D, it's also possible.
Here's a silly example:
struct ArrayList(T, alias capacity) {
private T[capacity] array;
private uint _length;
uint length() const => _length;
T get(uint index) const => array[index];
void add(T t) {
array[_length++] = t;
}
}
struct EmptyList(T) {
uint length() const => 0;
}
/// This will return a different type depending on the length argument,
/// which is like a Zig comptime argument.
/// We cannot return the type itself, but the result is very similar.
auto createArrayList(T, alias length)() {
static if (length == 0) {
return EmptyList!T();
} else {
return ArrayList!(T, length)();
}
}
void main()
{
import std.stdio;
auto empty = createArrayList!(int, 0);
writeln(empty);
auto list = createArrayList!(int, 2);
list.add(5);
list.add(6);
writeln(list);
}
Result: EmptyList!int()
ArrayList!(int, 2)([5, 6], 2)Regardless, we are now very far removed from the original code I was commenting on, which doesn't use auto to return different types.