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

Solidity编写mapping的getter函数触发数据位置TypeError如何解决

问题解决方法
  • 错误1:uint属于值类型,Solidity ^0.5.0版本仅要求数组、结构体、映射这类引用类型显式声明数据位置,值类型不需要加memory修饰,你给入参_id加了memory不符合语法规则。
  • 错误2、3:返回值中的string属于引用类型,^0.5.0版本要求返回的引用类型必须显式指定memory数据位置,你没有给两个string返回值加修饰导致报错。

额外优化建议:该函数仅读取链上数据不修改状态,可以加上view修饰符,避免调用时消耗不必要的gas。返回值的地址类型建议和结构体定义对齐,保留payable属性避免隐式类型转换风险。

修正后的完整代码
pragma solidity ^0.5.0;

struct Proyect{
    uint id; 
    string hash; 
    string name;
    address payable author; 
}

mapping(uint => Proyect) public proyects;

function getProyect(uint _id) public view returns (uint, string memory, string memory, address payable){
    Proyect memory _proyect = proyects[_id];
    return(_proyect.id, _proyect.hash, _proyect.name, _proyect.author);
}

如果不需要保留返回地址的payable属性,也可以将返回值最后一个参数改为address,和你原有写法兼容,不会触发报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 23:42:03