问题描述
在智能合约中,我添加了如下所示的功能。如何为此编写更新函数?
function addEmployee(
int empid,string memory name,string memory department,string memory designation
) public{
Employee memory e
=Employee(empid,name,department,designation);
emps.push(e);
解决方法
如果您知道保存所需 emps
的 Employee
数组的索引,您可以简单地重写该值。
function updateEmployee(
uint256 index,int empid,string memory name,string memory department,string memory designation
) public {
emps[index] = Employee(empid,name,department,designation);
}
如果您不知道索引并需要先找到它,您可以创建一个搜索索引的 view
函数(无需支付任何 gas 费用即可调用)。
以下是假设 empid
是唯一的搜索函数示例。如果 empid
不唯一,则函数只返回第一个找到的索引。
function getEmpsIndex(int empid) public view returns (uint256) {
for (uint256 i = 0; i < emps.length; i++) {
if (emps[i].empid == empid) {
return i;
}
}
revert('Did not find');
}
然后您可以使用此索引并将其传递给 updateEmployee()
函数。