I'd like to return struct type User. However, when I tried the following getUser function, it returns an error. Is there any way that struct data would be returned from a function?

Contract

struct User{
    uint256 user_id;
    bytes32 name;
    bytes32 address;
    bytes32 birth_day;
}
mapping (uint256 => User) public users;

function getUser(uint256 user_id) constant returns (User) {
        return users[user_id];
}

Error

client/lib/contracts/User.sol: Solidity errors: :125:58: Error: Expected type name
function getUser(uint256 user_id) constant returns (struct User) {

up vote 13 down vote accepted

You can not return a struct because Solidity implements them only as a loose bag of variables, they are not real objects.

You can use a solution from this answer: https://ethereum.stackexchange.com/a/3614/264

  • 3
    The answer is a year old. Are there any updates? Or we still can not return struct array from solidity function. – Prashant Prabhakar Singh Jul 29 '17 at 9:38

This will only work when the struct is passed around within the contract via the use of internal function calls. Even using ABIEncoderV2, when attempting to return a struct via a public or external function will give the following error: error: Failed to decode output: Error: Unsupported or invalid type: tuple

Passing structs is available in 0.4.17 with pragma experimental ABIEncoderV2. See https://github.com/ethereum/solidity/issues/40

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.