前言
在solidity 0.4 时代,是不支持返回struct的。但现在solidity已经进入了0.8的版本,这个版本是支持直接返回struct与struct array的,以下为具体做法。

代码示例

// 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调用结果

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' ]
]

我们看到,是以数字形式呈现的,其中struct值以 值+键值对 呈现。