6

I'm just trying to get confirmation as to whether this is supported within Solidity currently. Older responses to this question seem to imply this has been added, but I can't find any concrete literature to confirm.

If I have a struct within the contract, can I return it via a getter on the contract? For example:

struct myDetails {
    string firstName;
    string lastName;
}

function getName() returns (???) {
    return myName;
}

Thx

Marty

Marty Bell
  • 61
  • 2

2 Answers2

4

It's not currently possible to return a struct to the outside with your own function. Nonetheless, it's possible with Solidity's automatically generated getters.

By marking a variable public (for example uint public someNumber) Solidity will automatically generate a getter (someContract.someNumber()). This will indeed work on structs (Foo public someFoo) and even arrays and mappings! (mapping(uint => player) public players) In the last case, you provide a key to the getter to get the one you want. (someContract.players(7))

One caveat: Nested structs, arrays, and mappings inside of structs are currently not returned by getters. Strings, however, are.

Matthew Schmidt
  • 7,290
  • 1
  • 24
  • 35
  • In mapping(uint => player) public players, the value type player seems to be a user-defined, i.e. non-primitive type. So I presume it would be some struct or mapping. So if someContract.players(7) returns a player, does that mean that structs inside of mappings can be returned even though mappings inside of structs cannot (which you mention in the caveat later)? – Ajoy Bhatia Apr 20 '17 at 18:01
  • Structs can be retrieved through mappings by this method, yes. – Matthew Schmidt Apr 20 '17 at 21:29
  • Now it's 2018/1, is it still true that "It's not possible to return a struct to the outside with your own function"? Tried in Remix and seems it doesn't reject the idea of returning a struct completely. However it generates a compilation error which might be related. I asked a question here: https://stackoverflow.com/questions/48160495/why-the-struct-is-larger-than-32-bytes – Roy Jan 09 '18 at 02:11
0

in the official repos there is no indication about allowing a return of the struct type. check https://github.com/ethereum/solidity/releases

I suggest you to use multiple return for your getName function.

function getName() returns (string,string) {

 string firstName;
 string lastName;
  return (firstName, lastName);
}
Badr Bellaj
  • 18,780
  • 4
  • 58
  • 75