导入
函数
学习如何在 Solidity 中使用函数。
...
函数的工作原理
函数声明语法
1function <函数名>(<参数列表>) <作用域> returns() { 2 // 要执行的代码 3}
1// SPDX-License-Identifier: MIT 2pragma solidity ^0.8.17; 3contract Storage { 4 // 声明一个 uint 类型的状态变量 5 uint256 public number; 6 7 constructor() { 8 // 初始化状态变量 9 number = 1; 10 } 11 12 // 声明一个函数用于递增数值 13 function getIncrementedNumber() public view returns(uint) 14 { 15 // 局部变量 nonce 16 uint nonce = number + 1; 17 return nonce; 18 } 19}
1// SPDX-License-Identifier: MIT 2pragma solidity ^0.8.17; 3contract Storage { 4 // 声明一个 uint 类型的状态变量 5 uint256 public number; 6 7 constructor() { 8 // 调用 getIncrementNumber 函数 9 getIncrementedNumber(); 10 // 调用 incrementedNumberBy 函数 11 incrementedNumberBy(1); 12 } 13 14 // 声明一个函数用于递增数值 15 function getIncrementedNumber() public view returns(uint) 16 { 17 // 局部变量 Nonce 18 uint nonce = number + 1; 19 return nonce; 20 } 21 22 // 声明一个函数,根据传入的参数递增数值 23 function incrementedNumberBy(uint _num) public view returns(uint) 24 { 25 // 局部变量 nonce 26 uint nonce = number + _num; 27 return nonce; 28 } 29}
1// SPDX-License-Identifier: MIT 2pragma solidity ^0.8.17; 3contract Storage { 4 // 声明一个 uint 类型的状态变量 5 uint256 public number; 6 7 constructor() { 8 // 调用 incrementedNumberBy() 函数 9 incrementedNumberBy(1); 10 } 11 12 // 声明一个函数,根据传入的参数递增数值 13 function incrementedNumberBy(uint _num) public view returns(uint) { 14 // 定义一个名为 nonce 的局部变量 15 uint nonce = number + _num; 16 // 定义返回语句,返回 number 的最终结果 17 return nonce; 18 } 19}