Solidity中结构体返回值含索引重复值的原因解析
问题:Truffle调用Solidity函数返回结果同时包含索引键和命名键是否正常?
我正在学习Solidity结构体,写了一个待办事项示例合约:
// SPDX-License-Identifier: MIT pragma solidity ^0.8.17; contract Todos { struct Todo { string text; bool completed; } // An array of 'Todo' structs Todo[] public todos; function create(string calldata _text) public { // 3 ways to initialize a struct // - calling it like a function todos.push(Todo(_text, false)); // key value mapping todos.push(Todo({text: _text, completed: false})); // initialize an empty struct and then update it Todo memory todo; todo.text = _text; // todo.completed initialized to false todos.push(todo); } // Solidity automatically created a getter for 'todos' so // you don't actually need this function. function get(uint _index) public view returns (string memory text, bool completed) { Todo storage todo = todos[_index]; return (todo.text, todo.completed); } // update text function updateText(uint _index, string calldata _text) public { Todo storage todo = todos[_index]; todo.text = _text; } // update completed function toggleCompleted(uint _index) public { Todo storage todo = todos[_index]; todo.completed = !todo.completed; } }
在Truffle中调用get函数时,返回结果是:Result { '0': 'task 1', '1': true, text: 'task 1', completed: true },我预期只显示Result {text: 'task 1', completed: true },请问这个现象正常吗?为什么会同时出现索引和命名键?
回答:
- 这个现象完全正常,是Truffle处理Solidity函数返回值的默认行为。
- 核心原因是Solidity的ABI(应用二进制接口)规范要求函数返回值按位置顺序编码,这是区块链节点返回的原始数据格式;而你在函数
returns声明中给返回值添加了命名标识,Truffle为了方便开发者使用,会同时解析并提供两种访问形式:- 索引键(
'0'、'1'):对应ABI中按顺序排列的原始返回值,兼容底层数据格式。 - 命名键(
text、completed):对应你定义的返回值名称,让代码更具可读性。
- 索引键(
- 这种设计是为了兼顾不同使用场景,你可以根据需求选择用索引快速取值,或者用命名键提升代码可读性,两种形式都是有效的返回结果。
内容的提问来源于stack exchange,提问作者xmrrabbitx
相关产品推荐
相关产品推荐

