0

I'm trying to return a struct called Trainer from a mapping of addresses -> Trainer

Is there any way to easily retrieve the Trainer struct from the trainersMap?

struct Trainer {
    address owner;
    string name;
    Pokemon[] pokemons;
}

mapping(address => Trainer) public trainersMap;

function getTrainer() public {
    address sender = msg.sender;
    return Trainer(sender, trainersMap[sender].name, trainersMap[sender].pokemons);
    // I tried this
    // return trainersMap[sender]

}
1
  • What is Pokemon? Is it a struct?
    – Ismael
    Feb 28 at 5:28

1 Answer 1

0

You may not have properly created your function. This works for me. Plus, since trainersMap is already public, you could consider getTrainer() to be somewhat redundant. But it is my belief that setting an explicit getter is preferable to some.

pragma solidity ^0.8.0;

contract TrainerTest {

    struct Pokemon {
        uint64 element;
        uint64 cp;
    }

    struct Trainer {
        address owner;
        string name;
        Pokemon[] pokemons;
    }

    mapping(address => Trainer) public trainersMap;

    function getTrainer() public view returns(Trainer memory) {
        return trainersMap[msg.sender];
    }
}

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.