1

I want to use an iterating uint as an identifying number, but I have a simple question to make sure I can do this safely on the mainnet. Here's a simple example to demonstrate the issue:

pragma solidity ^0.5.8;

contract Names {

    uint lastId;
    mapping(uint => string) public numberedNames;

    constructor() public {
        lastId = 0;
    }

    function setName(string memory name) public {
        numberedNames[lastId] = name;
        lastId++;
    }
}

My question is that if setName gets called multiple times within the same block, is it possible that lastId does not get updated after the first call, thus overriding the previous numberedNames element?

2

No, it doesn't matter whether transactions are in the same block or not. Each transaction is processed on its own, sequentially. The code you propose is fine, though an array may make more sense.

  • In terms of an array making more sense, are you suggesting just to push the name onto the end of the array and use array indexes as as the identifier? Part of the reason I wanted to use a mapping is to allow for easier deleting. I'm not totally sure that I'll need to delete anything yet, but I'd think having to delete from an array while also maintaining the identifier would be messier. – SuperCodeBrah Jun 16 at 21:33
  • Deleting from an array works the same way. delete foo[5] will just zero out the storage used by foo[5], regardless of whether foo is a mapping or an array. – smarx Jun 16 at 21:37

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.