{"content":{"title":"Solidity require","body":"还有一个关键的 Solidity 关键字，然后我们就可以创建自己的 ERC20 代币了。\r\n\r\n虽然我们可以使用 `if` 语句来检查函数的输入是否有效，或者调用函数的是否是 `msg.sender`，但更优雅的方式是使用 `require` 语句。`require` 语句在某些条件不满足时，会强制回滚交易。\r\n\r\n```solidity\r\n\r\ncontract ExampleContract {\r\n    function mustNotBeFive(\r\n        uint256 x\r\n    )\r\n        public\r\n        pure\r\n        returns (uint256) {\r\n            require(x != 5, \"five is not valid\");\r\n            return x * 2;\r\n    }\r\n}\r\n\r\n```\r\n\r\n在 [Remix](https://remix.ethereum.org/) 中尝试上述代码。\r\n\r\n需要注意的是，省略错误信息是有效的，但被认为是不良实践，因为这会使理解失败原因变得更加困难。\r\n\r\n```solidity\r\n\r\ncontract ExampleContract {\r\n    function mustNotBeFive(\r\n        uint256 x\r\n    )\r\n        public\r\n        pure\r\n        returns (uint256) {\r\n            // 有效，但不推荐实践\r\n            require(x != 5);\r\n            return x * 2;\r\n    }\r\n}\r\n\r\n```\r\n\r\n你可以使用这种结构来确保 `msg.sender` 是预期的人。但你可以在以下问题中练习这一点。\r\n\r\n**练习问题**\r\n\r\n[NotEnough](https://github.com/RareSkills/Solidity-Exercises/tree/main/NotEnough)\r\n\r\n[Owner](https://github.com/RareSkills/Solidity-Exercises/tree/main/Owner)\r\n\r\n### 了解更多\r\n\r\n查看  [区块链训练营](https://learnblockchain.cn/openspace/1) ，以了解更多关于智能合约开发和代币标准的知识。\r\n \r\n\r\n>- 原文链接： [rareskills.io/learn-soli...](https://www.rareskills.io/learn-solidity/require)\r\n>- 登链社区 AI 助手，为大家转译优秀英文文章，如有翻译不通的地方，还请包涵～"},"author":{"user":"https://learnblockchain.cn/people/20722","address":null},"history":"bafkreidf3itd7r3qwxsgvcmrgt6vc2cf2ykcfhcsggajutjjh3azllec6m","timestamp":1740705581,"version":1}