Solidity 学习笔记
通过学习Solidity
,然后输出文章检验自己的学习成果Github仓库
欢迎大家关注我的X
引用类型
storage
获取该结构体的引用,以防止引用类型的数据丢失该例子是通过使用结构体(Struct)存储待办事项的例子
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract Todos {
struct Todo {
string text;
bool completed;
}
Todo[] public todos;
function createOneWay(string memory _text) public {
todos.push(Todo(_text, false));
}
function createTwoWay(string memory _text) public {
todos.push(Todo({text : _text, completed : false}));
}
function createThreeWay(string memory _text) public {
Todo memory todo;
todo.text = _text;
todos.push(todo);
}
function get(uint _index) public view returns (string memory text, bool completed){
Todo storage todo = todos[_index];
return (todo.text, todo.completed);
}
function update(uint _index, string memory _text) public {
Todo storage todo = todos[_index];
todo.text = _text;
}
function toggleCompleted(uint _index) public {
Todo storage todo = todos[_index];
todo.completed = !todo.completed;
}
}
struct Todo {
string text;
bool completed;
}
Todo[] public todos;
function createOneWay(string memory _text) public {
todos.push(Todo(_text, false));
}
function createTwoWay(string memory _text) public {
todos.push(Todo({text : _text, completed : false}));
}
function createThreeWay(string memory _text) public {
Todo memory todo;
todo.text = _text;
todos.push(todo);
}
Todo(_text, false)
,像函数调用一样初始化,这种方式不推荐,因为如果在结构体中间新增一个新的变量,所有初始化函数都需要改Todo({text : _text, completed : false})
,像键值对映射一样初始化,强烈推荐Todo memory todo
初始化一个结构体(Struct)变量,然后对其进行赋值function get(uint _index) public view returns (string memory text, bool completed){
Todo storage todo = todos[_index];
return (todo.text, todo.completed);
}
function update(uint _index, string memory _text) public {
Todo storage todo = todos[_index];
todo.text = _text;
}
function toggleCompleted(uint _index) public {
Todo storage todo = todos[_index];
todo.completed = !todo.completed;
}