7

Trying to do this:

contract Foo {
    mapping (bytes32 => Thing) things;

    struct Thing {
        Item[] items;
    }

    struct Item {
        uint number;
    }

    function Foo(bytes32 id) {
        Thing memory thing = Thing(); // What to do here to create empty array of type Item[]?
        things[id] = thing;
    }
}

and I get the error message:

Untitled:13:30: Error: Wrong argument count for function call: 0 arguments given but expected 1.
   Thing memory thing = Thing();

1 Answer 1

13

Some issues:

  1. The compiler does not yet support copying memory struct arrays to storage, so things[id] = thing; will fail.

  2. Thing thing; will initialize thing to a Thing with thing.items set to an empty array, so there's no need to use the constructor at all.

  3. Since all elements of mappings come pre-initialized to their "zero" values, there's no need to create a Thing in memory, then copy it to the mapping. Just assign values to the mapping's properties.


For example, this is the code I would use, with some added fields to better illustrate the concept:

contract Foo {
    mapping (bytes32 => Thing) things;

    struct Thing {
        Item[] items;
        uint _bar;
    }

    struct Item {
        uint number;
    }

    function Foo(bytes32 id, uint bar) {
        things[id]._bar = bar;
    }
}

This demonstrates how mapping elements are pre-initialized. things[id].items will return an empty Item[].

In addition, you can create an uninitialized Thing, and all of it's fields will default to zero (ore empty, false, etc.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.