solidity基础语法结构体Structs和存储位置

Posted 泠泠在路上

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了solidity基础语法结构体Structs和存储位置相关的知识,希望对你有一定的参考价值。

solidity语法中的结构体Structs

pragma solidity ^0.8.10;

contract Todos 
    struct Todo 
        string text;
        bool completed;
    

    // An array of 'Todo' structs
    Todo[] public todos;

    function create(string memory _text) public 
        // 3 ways to initialize a struct
        // - calling it like a function
        todos.push(Todo(_text, false));

        // key value mapping
        todos.push(Todo(text: _text, completed: false));

        // initialize an empty struct and then update it
        Todo memory todo;
        todo.text = _text;
        // todo.completed initialized to false

        todos.push(todo);
    

    // Solidity automatically created a getter for 'todos' so
    // you don't actually need this function.
    function get(uint _index) public view returns (string memory text, bool completed) 
        Todo storage todo = todos[_index];
        return (todo.text, todo.completed);
    

    // update text
    function update(uint _index, string memory _text) public 
        Todo storage todo = todos[_index];
        todo.text = _text;
    

    // update completed
    function toggleCompleted(uint _index) public 
        Todo storage todo = todos[_index];
        todo.completed = !todo.completed;
    

solidity存储位置

标记存储位置一般用:Storage, Memory 和 Calldata

storage存储状态变量
memory存储局部变量
calldata局部变量,只能用在输入的参数中

pragma solidity ^0.8.10;

contract DataLocations 
    uint[] public arr;
    mapping(uint => address) map;
    struct MyStruct 
        uint foo;
    
    mapping(uint => MyStruct) myStructs;

    function f() public 
        // call _f with state variables
        _f(arr, map, myStructs[1]);

        // get a struct from a mapping
        MyStruct storage myStruct = myStructs[1];
        // create a struct in memory
        MyStruct memory myMemStruct = MyStruct(0);
    

    function _f(
        uint[] storage _arr,
        mapping(uint => address) storage _map,
        MyStruct storage _myStruct
    ) internal 
        // do something with storage variables
    

    // You can return memory variables
    function g(uint[] memory _arr) public returns (uint[] memory) 
        // do something with memory array
    

    function h(uint[] calldata _arr) external 
        // do something with calldata array
    

以上是关于solidity基础语法结构体Structs和存储位置的主要内容,如果未能解决你的问题,请参考以下文章

区块链开发之Solidity编程基础

C语言,宏定义和结构体指针问题,求高手解答啊,谢谢了!!

字节对齐-------结构体共用体

solidity 语法学习

solidity语法3——全局变量,表达式,控制结构

Swift2.0结构体类型&枚举类型