3分钟Solidity: 3.3 Enum枚举

如需获取本内容的最新版本,请参见 Cyfrin.io 上的 Enum(代码示例)

Solidity支持枚举类型,它们非常适合用于建模选择项和跟踪状态。 枚举可以在合约外部声明。

solidity 复制代码
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

contract Enum {
    // 表示运输状态的枚举
    enum Status {
        Pending,
        Shipped,
        Accepted,
        Rejected,
        Canceled
    }

    // 默认值是类型定义中列出的第一个元素,本例中为"Pending"
    Status public status;

    // 返回无符号整数
    // Pending  - 0
    // Shipped  - 1
    // Accepted - 2
    // Rejected - 3
    // Canceled - 4
    function get() public view returns (Status) {
        return status;
    }

    // 通过将无符号整数传递到输入来更新状态
    function set(Status _status) public {
        status = _status;
    }

    // 你可以像这样更新到特定的枚举
    function cancel() public {
        status = Status.Canceled;
    }

    // 删除会将枚举重置为其第一个值,0
    function reset() public {
        delete status;
    }
}

Remix Lite 尝试一下

声明和导入枚举

声明枚举的文件

solidity 复制代码
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
// 这是保存的'EnumDeclaration.sol'

enum Status {
    Pending,
    Shipped,
    Accepted,
    Rejected,
    Canceled
}

Remix 尝试一下

导入上述枚举的文件

solidity 复制代码
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

import "./EnumDeclaration.sol";

contract Enum {
    Status public status;
}

Remix Lite 尝试一下


END

相关推荐
OxYGC5 天前
[Web3] 智能合约 19: NFT 知识与 Web3 求职指南
区块链·智能合约·求职招聘·nft
OxYGC6 天前
[Web3] 智能合约 18: 借贷之 Compound V2 源码解读
web3·智能合约
OxYGC6 天前
[Web3] 智能合约 00: 系列总览与目录
web3·区块链·智能合约·solidity
木西6 天前
别再只听概念了!手把手手搓图币二象性合约|DN-404 极简实战
web3·智能合约·solidity
Bczheng17 天前
五十六.网络(6)--广播tx测试
区块链
OxYGC7 天前
[Web3] 智能合约 15: 项目实战⑦ 从0到1 体育投注
web3·智能合约
OxYGC8 天前
[Web3] 智能合约 13: 项目实战⑤ DappLink Oracle
oracle·web3·智能合约
木西11 天前
深度拆解 MyShell 底层:AI Agent 生态结算合约,如何实现安全防阻塞
web3·智能合约·solidity
笑容掩饰我的失落12 天前
区块链从小白到精通(十):合约安全与上线——重入攻击、Gas 优化与最佳实践
安全·区块链
Cooper2512 天前
合约托管 + 验收释放:悬赏 DApp 的四态状态机与事件索引
web3·solidity