12.Enum

Solidity支持枚举类型,它们对于建模选择和跟踪状态非常有用。枚举类型可以在合约之外声明。枚举类型将变量限制为仅具有少数预定义值之一。在这个枚举列表中的值称为枚举。通过使用枚举类型,可以减少代码中的错误数量。

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;

contract Enum {
    enum Status {
        None,
        Pending,
        Shipped,
        Completed,
        Rejected,
        Canceled
    }

    Status public status;

    struct Order {
        address buyer;
        Status status;
    }

    Order[] public orders;

    function get() external view returns (Status) {
        return status;
    }

    function set(Status _status) external {
        status = _status;
    }

    function ship() external {
        status = Status.Shipped;
    }

    function reset() external {
        delete status;
    }
}

我想知道,为什么 get() 为什么要加上external和view?

在Solidity中,函数可以有不同的可见性和状态修改器。

"external"关键字表示该函数只能从合约外部调用,而不能从合约内部调用。

"view"关键字表示该函数不会修改合约状态,因此可以在不消耗gas的情况下从外部调用。

因此,"get"函数需要同时使用这两个关键字,以确保它可以从外部调用,并且不会修改合约状态。

Solidity支持可枚举类型,它们用于模拟选择并跟踪状态。可枚举类型可以在合约之外声明。可枚举类型将变量限制为仅具有少数预定义的值之一。在此枚举列表中的值称为枚举。通过使用可枚举类型,可以减少代码中的错误数量。

例如,如果我们考虑一个新鲜果汁店的应用程序,可以将玻璃杯尺寸限制为小、中、大三种尺寸。这将确保不允许任何人订购除小、中、大之外的任何尺寸。

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract test {
   enum FreshJuiceSize{ SMALL, MEDIUM, LARGE }
   FreshJuiceSize choice;
   FreshJuiceSize constant defaultChoice = FreshJuiceSize.MEDIUM;

   function setLarge() public {
      choice = FreshJuiceSize.LARGE;
   }
   function getChoice() public view returns (FreshJuiceSize) {
      return choice;
   }
   function getDefaultChoice() public pure returns (uint) {
      return uint(defaultChoice);
   }
}

import

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "./EnumDeclaration.sol";

contract Enum {
    Status public status;
}