Renaissance Labs

Posted on Feb 25, 2022Read on Mirror.xyz

Learn Solidity Series 6: CRUD delete

Learn Solidity Series

delete

它用于将变量设置为其初始值,这意味着该语句delete a的行为如下:

对于整数,它等于a = 0。 对于数组,它分配长度为零的动态数组或长度相同的静态数组,并将所有元素设置为其初始值。 delete a[x]删除数组索引x处的项目,并保持所有其他元素和数组长度不变。这尤其意味着它在数组中留有间隙。 对于结构体,它将重置结构体的所有成员。 delete对映射没有影响(因为映射的键可能是任意的,并且通常是未知的)。

CRUD

可见性(visibiliity)可以是:public,private,internal,external。 状态可变性(state mutability)可以是:view,pure,payable。

Follow code will 创建的函数的描述:

  1. add 可见性:public 状态可变性:空

此函数将用户名作为参数,使用新ID创建User实例(每次添加新用户时ID都会自动递增),并将新创建的用户添加到数组中。

  1. read 可见性:public 状态可变性:view

此函数获取要查找的用户的ID,如果找到则返回用户名,否则回退(稍后会详细讨论异常)。

  1. update 可见性:public 状态可变性:空

此函数将获取用户的ID和新名称,然后在找到相应用户时对其进行更新,如果该用户不存在,则回退该交易。

  1. destroy 可见性:public 状态可变性:空

此函数将用户的ID删除,如果找到,则将其从数组中删除;如果用户不存在,则回退交易。

提示:由于最后三个函数都需要查找用户,因此你将需要创建一个私有函数,该函数将获取用户的ID并在数组中返回其索引(如果找到),以避免重复相同的代码。

// SPDX-License-Identifier: MIT
 
pragma solidity ^0.7.0;
 
contract Crud {
    
    struct User {
        uint256 id;
        string name;
    }
    
    User[] public users;
    uint256 public nextId = 1;
    
    function add(string memory name) public {
        User memory user = User({id : nextId, name : name});
        users.push(user);
        nextId++;
    }
    
    function read(uint256 id) public view returns(string memory){
        uint256 i = find(id);
        return users[i].name;
    }
    
    function update(uint256 id, string memory newName) public {
        uint256 i = find(id);
        users[i].name = newName;
    }
    
    function destroy(uint256 id) public {
        uint256 i = find(id);
        delete users[i];
    }
    
    function find(uint256 id) private view returns(uint256){
        for(uint256 i = 0; i< users.length; i++) {
            if(users[i].id == id)
                return i;
        }
        revert("User not found");
    }
    
}