Solidity ParserError: Expected identifier but got '='

baermathias picture baermathias · Jul 7, 2018 · Viewed 14.5k times · Source

Why does the code below contain an error (ParserError: Expected identifier but got '=').

contract Test {

    struct Box {
        uint size;
    }

    Box public box;
    box.size = 3;    //<-- error here

    constructor() public {
    }

}

It works if I put the box.size = 3; into the constructor!

contract Test {

    struct Box {
        uint size;
    }

    Box public box;

    constructor() public {
        box.size = 3;
    }

}

Answer

The grammar doesn't allow assignments on contract level. But it allows declarations of state variables and these can contain an initializer. Therefore you can initialize it with

Box public box = Box({ size: 3 });

or

Box public box = Box(3);