# Learn Solidity Series 6: CRUD delete **Published by:** [ht222](https://paragraph.com/@ht222/) **Published on:** 2022-03-18 **URL:** https://paragraph.com/@ht222/learn-solidity-series-6-crud-delete ## Content Learn Solidity Series 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 创建的函数的描述: add\ 可见性:public 状态可变性:空 此函数将用户名作为参数,使用新ID创建User实例(每次添加新用户时ID都会自动递增),并将新创建的用户添加到数组中。 read\ 可见性:public 状态可变性:view 此函数获取要查找的用户的ID,如果找到则返回用户名,否则回退(稍后会详细讨论异常)。 update\ 可见性:public 状态可变性:空 此函数将获取用户的ID和新名称,然后在找到相应用户时对其进行更新,如果该用户不存在,则回退该交易。 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"); } } ## Publication Information - [ht222](https://paragraph.com/@ht222/): Publication homepage - [All Posts](https://paragraph.com/@ht222/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@ht222): Subscribe to updates