Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Struct Initialization

Part of TutorialFundamentals

Description

Shows different ways of initializing struct types.

Example

import std.stdio;

struct Foo
{
    int a;
    int b;
    int c;
}

void main()
{
    /* #1 */
    Foo foo1 = Foo();        
    
    /* #2 */
    Foo foo2 = Foo(1, 2);
    
    /* #3 */
    static Foo foo3 = { c: 3, b: 2, a: 1 };

    /* #4 */
    Foo foo4 = { 1, 2, 3 };     

    /* #5: Arrays of Foo structs */
    Foo[] foo5 = [Foo(), Foo()];
    
    Foo[] foo6 = [Foo(1, 2), Foo(3, 4, 5)];
    
    static Foo[] foo7 = [{ a: 1, b: 2, c: 3 }, { c: 4, b: 5, a: 6 }];
    
    Foo[] foo8 = [{ 1, 2, 3 }, { 4, 5, 6 }];
}

Explanation

1: Calling a structure type with empty parantheses ( structType() ) constructs a struct with all of its fields initialized to their type's .init property.

2: Calling a structure type with arguments will initialize the struct's fields in the order of the field declarations. In this case foo2.a is initialized to 1, foo2.b to 2. Notice that you don't have to provide all of the arguments, foo3.b will be initialized to int.init, which is 0.

3: This is the static initializer syntax, used for initializing static variables.

4: This is another form of the static initializer syntax. However, if explicit field names are not used, then this syntax may be used to initialize non-static variables.

5 and onwards: Initializing an array of Foo structs is conceptually the same as initializing a single Foo struct. The difference is that you have to use the array literal syntax. This enables you to provide multiple struct initializers, with the simple convention of the syntax [ init1, init2, initN ].

More Information

More information on the usage of struct initializers can be found in the Phobos documentation.