I wrote a function that returns mapping type which contains all the tokenID and owner of the tokenID. But I get the following error when compiling.

error: TypeError: Data location must be "memory" or "calldata" for return parameter in function, but none was given.


    mapping(uint256 => address) public tokenIdAndOwner;
    function tokensAndOwner() public view returns (mapping(uint256 => address)){
        return tokenIdAndOwner;

Is it possible to return mapping type in solidity? I am using solidity 0.8.7

Thank you

2 Answers 2


According to the Solidity docs you cannot return a mapping:

Mappings can only have a data location of storage and thus are allowed for state variables, as storage reference types in functions, or as parameters for library functions. They cannot be used as parameters or return parameters of contract functions that are publicly visible. These restrictions are also true for arrays and structs that contain mappings.

Taken from https://docs.soliditylang.org/en/v0.8.11/types.html#mapping-types

The error you mentioned is because it is necessary to define the data location for the return parameter(s) (see https://docs.soliditylang.org/en/v0.8.11/types.html?highlight=mapping#data-location), which needs to be memory or calldata (another reason that you cannot use a mapping, as it only exists in storage)


give that:

mapping(uint256 => address) public tokenIdAndOwner;

Because tokenIdAndOwner is public, a "getter()" is created for it. So, it can be retrieved as a function call. However, the "key", in this case uint256 tokenId,must be passed in as a parameter. The getter() will then return the corresponding address.

This can also be proved in the following contract:

// SPDX-License-Identifier: MIT
pragma solidity 0.8.15;
contract MappingRetrieval {
mapping(uint256 => address) public intToAddr;
    constructor() {
        intToAddr[123] = msg.sender;
    function getMapping(uint256 key) public view returns(address) {
        // Note: Pass (123) into this function to retrieve corresponding address
        return intToAddr[key];

You can invoke both of the following: intToAddr(123); getMapping(123)

Just note you cannot retrieve the entire mapping in a single request. Given a single key, you can return its value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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