How to declare a parameterized recursive data structure?

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Fri Aug 15 11:42:35 PDT 2014


On Fri, Aug 15, 2014 at 06:37:51PM +0000, artemav via Digitalmars-d wrote:
> I'm getting an error when trying to compile (DMD64 D Compiler v2.066) this:
> 
> struct node(T) {
>     T data;
>     node!T next;
> };
> 
> void main() {
>     node!int n;
> }
> 
> output:
> test.d(3): Error: struct test.node!int.node cannot have field next with same
> struct type
> test.d(9): Error: template instance test.node!int error instantiating
> ...
> 
> It is so simple code that the error "... cannot have field next with
> same struct type" looks funny and sad at the same time. Is it a bug or
> are there some constraints why it cannot be compiled?

This has nothing to do with the struct being parametrized or not.
Structs are value types, so defining a struct in terms of itself would
make it infinitely large. That's why it's invalid.

I'm guessing what you *really* want is to keep a pointer to another
struct of the same type, in which case what you're looking for is:

	struct node(T) {
		T data;
		node* next;	// Note: it's not necessary to specify
				// !T here, if you want, you can write
				// it as: node!T* next;
	}


T

-- 
Having a smoking section in a restaurant is like having a peeing section in a swimming pool. -- Edward Burr 


More information about the Digitalmars-d mailing list