Copyright © 2022-2025 aizws.net · 网站版本: v1.2.6·内部版本: v1.25.2·
页面加载耗时 0.00 毫秒·物理内存 113.3MB ·虚拟内存 1372.4MB
欢迎来到 AI 中文社区(简称 AI 中文社),这里是学习交流 AI 人工智能技术的中文社区。 为了更好的体验,本站推荐使用 Chrome 浏览器。
函数是一组可重用代码的包装,接受输入,返回输出。
Solidity 支持函数定义和调用。
Solidity中, 定义函数的语法如下:
function function_name(<parameter list>) <visibility> <state mutability> [returns(<return type>)] {
//语句
}
函数由关键字function声明,后面跟函数名、参数、状态可变性、可见性、返回值的定义。
函数的可见性有四种:
下面的例子,定义了一个名为getResult的函数,该函数不接受任何参数:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Test {
function getResult() public view returns(uint){
uint a = 1; // 局部变量
uint b = 2;
uint result = a + b;
return result;
}
}
要调用函数,只需使用函数名,并传入参数即可。
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SolidityTest {
constructor() {
}
function getResult() public pure returns(string memory){
return integerToString(3); // 调用函数 integerToString
}
// integerToString 函数定义 function integerToString(uint _i) internal pure
returns (string memory) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
}
运行上述程序,输出:
0: string: 3
Solidity中, 函数可以返回多个值。
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Test {
function getResult() public view returns(uint product, uint sum){
uint a = 1; // 局部变量
uint b = 2;
product = a * b; // 使用返回参数返回值
sum = a + b; // 使用返回参数返回值
// 也可以使用return返回多个值
// return(a*b, a+b);
}
}
运行上述程序,输出:
0: uint256: product 2 1: uint256: sum 3
Solidity 函数的返回值可以使用名字,也可以采用匿名方式。Solidity 函数的返回值可以通过名字赋值,也可以使用 return 返回。Solidity 函数支持多个返回值。// SPDX-Licens ...