Solidity ParserError:预期标识符但得到“=”

sai*_*tam 4 constructor identifier parsing-error ethereum solidity

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

contract Test {

    struct Box {
        uint size;
    }

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

    constructor() public {
    }

}
Run Code Online (Sandbox Code Playgroud)

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

contract Test {

    struct Box {
        uint size;
    }

    Box public box;

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

}
Run Code Online (Sandbox Code Playgroud)

Ant*_*ala 5

语法不允许在合同级别进行分配。但它允许声明状态变量,并且这些变量可以包含一个初始化程序。因此你可以用

Box public box = Box({ size: 3 });
Run Code Online (Sandbox Code Playgroud)

或者

Box public box = Box(3);
Run Code Online (Sandbox Code Playgroud)