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

Solidity返回struct时报string storage pointer转string memory类型错误

报错原因

你遇到的TypeError Invalid type. Invalid implicit conversion from type (string storage pointer) to string memory requested报错,核心是三个问题叠加:

  • struct初始化语法错误:return语句中直接传入string、uint等类型名作为参数,而非实际的变量值或字面量,语法本身不合法
  • 引用类型存储位置不匹配:struct内的string属于storage引用类型,直接作为公共函数返回值时,没有显式指定为memory类型,编译器无法完成隐式转换
  • 版本兼容限制:Solidity 0.7.x及更早版本不支持公共函数直接返回自定义struct类型,旧版本编译器会校验不通过

可行解决方案

方案1:升级到Solidity 0.8.x版本(推荐)

0.8+版本已支持公共函数直接返回struct类型,只需要修正初始化语法,显式指定返回struct的存储位置为memory即可:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Demo {
    struct Briefing {
        string description;
        uint max_influencer;
        uint jobvalue;
        bool achievement;
    }

    // 显式指定返回的struct为memory类型
    function getSummary() public view returns (Briefing memory) {
        // 传入实际要返回的值,而非类型名
        return Briefing({
            description: "任务描述",
            max_influencer: 10,
            jobvalue: 100,
            achievement: true
        });
    }
}

方案2:低版本兼容写法

如果需要兼容0.7.x及更早的Solidity版本,将struct字段拆分后逐个返回即可:

// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;

contract Demo {
    struct Briefing {
        string description;
        uint max_influencer;
        uint jobvalue;
        bool achievement;
    }

    // 示例存储的struct数据
    Briefing internal taskData = Briefing("测试任务", 5, 50, false);

    // 拆分字段返回,string显式指定为memory
    function getSummary() public view returns (string memory, uint, uint, bool) {
        return (
            taskData.description,
            taskData.max_influencer,
            taskData.jobvalue,
            taskData.achievement
        );
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 23:00:01