5

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

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.

  • 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: stackoverflow.com/questions/48160495/… – Roy Jan 9 '18 at 2: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);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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