Solidity ParserError: Expected identifier but got '='

Solidity ParserError: Expected identifier but got '='

为什么下面的代码包含错误 (ParserError: Expected identifier but got '=')。

contract Test {

    struct Box {
        uint size;
    }

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

    constructor() public {
    }

}

如果我将 box.size = 3; 放入 constructor!

contract Test {

    struct Box {
        uint size;
    }

    Box public box;

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

}

语法不允许在合同级别进行赋值。但它允许声明状态变量和 these can contain an initializer。因此你可以用

初始化它
Box public box = Box({ size: 3 });

Box public box = Box(3);