0

I have this function to check if an array has duplicates:

function hasDuplicates(uint256[] memory _array) internal pure returns (bool) {
    mapping(uint256 => bool) seen;

    for (uint256 i = 0; i < _array.length; i++) {
        if (seen[_array[i]]) {
            return true;
        } else {
            seen[_array[i]] = true;
        }
    }
    return false;
}

but I get Data location must be "storage", "memory" or "calldata" for variable, but none was given. when I try to define mapping(uint256 => bool) seen;

1 Answer 1

4

This is not allowed in solidity. You can't dynamically define mappings inside a function as it can be only defined as a storage variable.

From docs :

enter image description here

By storage reference it means something like this:

contract a {
    mapping(uint256 => bool)  aseen;

function hasDuplicates(uint256[] memory _array)
    internal
    
    returns (bool)
{
    mapping(uint256 => bool) storage seen = aseen;

    for (uint256 i = 0; i < _array.length; i++) {
        if (seen[_array[i]]) {
            return true;
        } else {
            seen[_array[i]] = true;
        }
    }
    return false;
}
}
1
  • 1
    Ok thank you, from the error output wasn't clear
    – viac92
    Commented Aug 29, 2023 at 9:48

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.