繁体   English   中英

智能合约更新功能

[英]Smart Contract update Function

在智能合约中,我添加了如下所示的功能。 如何为此编写更新功能?

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);

如果您知道保存所需Employeeemps数组的索引,则可以简单地重写该值。

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()函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM