Solidity - 库
库与合约类似,但主要用于重用。 库包含其他合约可以调用的函数。 Solidity 对库的使用有一定的限制。 以下是 Solidity 库的主要特征。
库函数如果不修改状态就可以直接调用。 这意味着纯函数或视图函数只能从库外部调用。
库无法被销毁,因为它被假定为无状态。
库不能有状态变量。
库不能继承任何元素。
库不能被继承。
示例
尝试以下代码来了解库在 Solidity 中的工作原理。
pragma solidity ^0.5.0;
library Search {
function indexOf(uint[] storage self, uint value) public view returns (uint) {
for (uint i = 0; i < self.length; i++) if (self[i] == value) return i;
return uint(-1);
}
}
contract Test {
uint[] data;
constructor() public {
data.push(1);
data.push(2);
data.push(3);
data.push(4);
data.push(5);
}
function isValuePresent() external view returns(uint){
uint value = 4;
//search if value is present in the array using Library function
uint index = Search.indexOf(data, value);
return index;
}
}
使用 Solidity First 应用 章节中提供的步骤运行上述程序。
注意 − 单击部署按钮之前,从下拉列表中选择测试。
输出
0: uint256: 3
Using For
指令using A for B;可用于将库A的库函数附加到给定类型B。这些函数将使用调用者类型作为它们的第一个参数(使用self标识)。
示例
尝试以下代码来了解库在 Solidity 中的工作原理。
pragma solidity ^0.5.0;
library Search {
function indexOf(uint[] storage self, uint value) public view returns (uint) {
for (uint i = 0; i < self.length; i++)if (self[i] == value) return i;
return uint(-1);
}
}
contract Test {
using Search for uint[];
uint[] data;
constructor() public {
data.push(1);
data.push(2);
data.push(3);
data.push(4);
data.push(5);
}
function isValuePresent() external view returns(uint){
uint value = 4;
//Now data is representing the Library
uint index = data.indexOf(value);
return index;
}
}
使用 Solidity First 应用 章节中提供的步骤运行上述程序。
注意 − 单击部署按钮之前,从下拉列表中选择测试。
输出
0: uint256: 3