Return mapping type in solidity

remixsolidityweb3js

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.

Code:

    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

Best Answer

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)