[Solidity development] contract function returns struct or struct array

foreword

In the era of solidity 0.4, returning struct is not supported. But now solidity has entered version 0.8, this version supports direct return of struct and struct array, the following is the specific method.

code example

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

contract ContractFactory {
    
    
    
    struct User {
    
    
        uint256 id;
        uint256 age;
        string name;
    }
    
    mapping(uint256 => User) public users;
    
    mapping(uint256 => User[]) public userGroup;
    
    function init() public {
    
    
        User memory newUser1 = User({
    
    
            id: 1,
            age: 24,
            name: "lily"
        });
        User memory newUser2 = User({
    
    
            id: 2,
            age: 25,
            name: "brain"
        });
        userGroup[1].push(newUser1);  
        userGroup[1].push(newUser2);      
        
        User storage newUser = users[1];
        newUser.age = 16;
        newUser.name = "amber";
        userGroup[1].push(newUser);
    }
    
    function getStruct() public view returns (User memory) {
    
    
        User memory user = users[1];
        return user;
    }
    
    function getStructArray() public view returns (User[] memory) {
    
           
        User[] memory group = userGroup[1];
        return group;
    }
    
    function getStructArrayLength() public view returns(uint256) {
    
    
        return userGroup[1].length;
    }
}

web3 call result

getStruct() ::  [ '0', '16', 'amber', id: '0', age: '16', name: 'amber' ]
getStructArray() ::  [
  [ '1', '24', 'lily', id: '1', age: '24', name: 'lily' ],
  [ '2', '25', 'brain', id: '2', age: '25', name: 'brain' ],
  [ '0', '16', 'amber', id: '0', age: '16', name: 'amber' ]
]

We see that it is presented in digital form, where the struct value is presented as a value + key-value pair.

Guess you like

Origin blog.csdn.net/weixin_43742184/article/details/120202987