You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Solidity中返回结构体数组?ERC721质押合约问题求助

ERC721质押合约:返回结构体数组的Getter函数修正

问题根源

原代码存在两处核心错误:

  1. 函数返回类型声明为uint256[],与期望返回的Stake结构体数组类型不匹配
  2. 临时数组tmp定义为uint256[],无法存储Stake结构体实例

修正后的代码

// 结构体与映射定义保持不变
struct Stake {
    uint256 tokenId;
    uint256 lockPeriod;
    uint256 startDate;
    address owner;
}

mapping(uint256 => Stake) public vault; 

// 修正后的Getter函数
function getNftInfo(uint256[] calldata tokenIds) public view returns (Stake[] memory) { 
    Stake[] memory tmp = new Stake[](tokenIds.length);
    for (uint i = 0; i < tokenIds.length; i++) {
        uint256 tokenId = tokenIds[i];
        tmp[i] = vault[tokenId];
    }
    return tmp;
}

关键说明

  • Solidity支持直接返回结构体数组,只要结构体在合约中可见(当前代码中Stake为合约内部定义,public函数返回它会自动生成兼容ABI的输出)
  • 调用该函数传入[1,345,10]这类tokenId数组时,会返回对应位置的Stake结构体数组,包含所有字段数据
  • 若tokenId未存在质押记录,返回的对应结构体字段会是默认值(uint256为0,address为0x0000000000000000000000000000000000000000),可按需添加判断逻辑过滤无效条目

内容的提问来源于stack exchange,提问作者Pietro Ciattaglia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 06:27:29