I have this mapping:

mapping (uint256 => string ) private storedData;

I am trying to do this:

modifier dataNotStored(uint256 _index) {
        require( keccak256(abi.encodePacked(storedData[_index])) == keccak256(abi.encodePacked('')) );

    function set(uint _index, string calldata _data_to_store) external dataNotStored(_index) {
        storedData[_index] = _data_to_store;

My goal is to allow only one write for each entry of the mapping.

I think it is working, because from Remix IDE I get error only when trying a rewrite.

Is there a more efficient and intelligent way to avoid to overwrite a mapping?

| improve this question | | | | |

You can avoid the modifier and the hashing. It is simpler to do:

function set(uint _index, string calldata _data_to_store) external {
    require(bytes(storedData[_index]).length == 0);
    storedData[_index] = _data_to_store;

Checking the length of the bytes was inspired by this answer.

| improve this answer | | | | |
  • 1
    Side question: is more efficient a require or a modifier – realtebo Jan 22 at 17:03
  • 1
    @realtebo: modifier is just sugar-syntax. It has no impact on the output byte-code, hence no impact on gas-cost performance. – goodvibration Jan 22 at 17:17

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.