Hello all --

I have a question about assigning to structs.

I want to be able to create an array of structs that may contain different contents depending on user input. I have reduced the test case down.

The following fails to compile:

```d
import std.stdio;

struct item
{
    string name;
    int type;
};

item[] items;

void main(string[] args)
{
    item new_item;

    for (int i = 0; i < args.length; i++) {
        if (args[i] == "item1") {
            new_item = { "item1", 1 };
        } else if (args[i] == "item2") {
            new_item = { "item2", 2 };
        } else {
            new_item = { "item3", 3 };
        }

        items ~= new_item;
    }

    for (int i = 0; i < items.length; i++)
        writeln(items[i].name);
}
```

This fails (dmd 2.097) with the following:
```d
struct_bad.d(17): Error: found `}` when expecting `;` following statement struct_bad.d(17): Deprecation: use `{ }` for an empty statement, not `;` struct_bad.d(18): Error: found `else` when expecting `;` following statement struct_bad.d(19): Error: found `}` when expecting `;` following statement struct_bad.d(19): Deprecation: use `{ }` for an empty statement, not `;` struct_bad.d(20): Error: found `else` when expecting `;` following statement struct_bad.d(21): Error: found `}` when expecting `;` following statement struct_bad.d(21): Deprecation: use `{ }` for an empty statement, not `;` struct_bad.d(24): Error: found `items` when expecting `;` following statement
struct_bad.d(24): Error: found `~=` instead of statement
struct_bad.d(30): Error: found `End of File` when expecting `}` following compound statement struct_bad.d(30): Error: found `End of File` when expecting `}` following compound statement struct_bad.d(30): Error: found `End of File` when expecting `}` following compound statement
```

However, a slight tweak allows the code to compile and work correctly.
```d
import std.stdio;

struct item
{
    string name;
    int type;
};

item[] items;

void main(string[] args)
{
    for (int i = 0; i < args.length; i++) {
        if (args[i] == "item1") {
            item new_item = { "item1", 1 };
            items ~= new_item;
        } else if (args[i] == "item2") {
            item new_item = { "item2", 2 };
            items ~= new_item;
        } else {
            item new_item = { "item3", 3 };
            items ~= new_item;
        }
    }

    for (int i = 0; i < items.length; i++)
        writeln(items[i].name);
}
```

I guess I am unclear as to why the first fails and the second succeeds.

TIA.

~Brian

Reply via email to