Solidity Tutorial for Beginners: 8. Initial Value of Variables

Solidity Tutorial for Beginners: 8. Initial Value of Variables

variable initial value

In Solidity , variables declared but not assigned a value have their initial or default values. In this lecture, we will introduce the initial values ​​of commonly used variables.

value type initial value

  • boolean: false
  • string: “”
  • int: 0
  • uint: 0
  • enum : the first element in the enumeration
  • address: 0x0000000000000000000000000000000000000000 (或 address(0))
  • function
    • internal : blank equation
    • external : blank equation

You can use the getter function of the public variable to verify whether the initial value written above is correct:

bool public _bool; // false
    string public _string; // ""
    int public _int; // 0
    uint public _uint; // 0
    address public _address; // 0x0000000000000000000000000000000000000000

    enum ActionSet { Buy, Hold, Sell}
    ActionSet public _enum; // 第1个内容Buy的索引0

    function fi() internal{} // internal空白方程
    function fe() external{} // external空白方程

Reference type initial value

  • Mapping : all elements are mapped to their default values
  • Structure struct : A structure with all members set to their default values
  • arrayarray _
    • Dynamic array: []
    • Static array (fixed length): a static array with all members set to their default values

You can use the getter function of the public variable to verify whether the initial value written above is correct:

// Reference Types
    uint[8] public _staticArray; // 所有成员设为其默认值的静态数组[0,0,0,0,0,0,0,0]
    uint[] public _dynamicArray; // `[]`
    mapping(uint => address) public _mapping; // 所有元素都为其默认值的mapping
    // 所有成员设为其默认值的结构体 0, 0
    struct Student{
        uint256 id;
        uint256 score;
    }
    Student public student;

delete operator

Delete a will change the value of variable a to its initial value.

// delete操作符
    bool public _bool2 = true;
    function d() external {
        delete _bool2; // delete 会让_bool2变为默认值,false
    }

Verify on remix

  • Deploy the contract to view the initial values ​​of value types and reference typesimage.png
  • Value type, reference type default value after delete operationimage.png

Summarize

In this lecture, we introduced the initial values ​​of variables in solidity . When a variable is declared but not assigned a value, its value defaults to its initial value. Different types of variables have different initial values. The delete operator can delete the value of a variable and replace it with the initial value.

Guess you like

Origin blog.csdn.net/weixin_52148451/article/details/132666099