How to return array of struct?

Viewed 2658

Function getBets() gives me the error: error: Failed to decode output: Error: Unsupported or invalid type: tuple. What am I missing?

pragma solidity ^0.4.11;

contract Casino {

    struct Bet {
        address by;
        uint number;
    }

    address owner;
    Bet[] bets;

    event BetPlaced(Bet bet);

    function Casino() {
        owner = msg.sender;
    }

    function bet(uint number) {
        Bet memory bet;
        bet.by = msg.sender;
        bet.number = number;

        bets.push(bet);

        BetPlaced(bet);
    }

    function getBets() constant returns (Bet[]) {
        return bets;
    }

    function getCount() constant returns (uint length) {
        return bets.length;
    }
}
2 Answers

At the moment if I'm correct you can't return anything except an array of integers as there is no support for returning multi-dimensional data storages;

You can use an experimental library using:

pragma experimental ABIEncoderV2;

in the place of:

pragma solidity ^0.4.11;

This isn't available on Remix if you're using that at the moment and it's experimental so it may never be part of Solidity source: https://github.com/ethereum/solidity/issues/2948

If you did want to return an array of structs you could convert the whole array to bytes and return the bytes. This would be a bit of an extreme case and I wouldn't advise it.

If you only need to access the method internally and not externally you can pass by storage e.g.

function getBets() internal returns (Bet[] storage _r) {
    _v = bets;
}
Related