contract_storage.rst 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. Contract Storage
  2. ================
  3. Any variables declared at the contract level (so not declared in a function or constructor),
  4. will automatically become contract storage. Contract storage is maintained on chain, so they
  5. retain their values between calls. These are declared so:
  6. .. include:: ../examples/contract_storage.sol
  7. :code: solidity
  8. The ``counter`` is maintained for each deployed ``hitcount`` contract. When the contract is deployed,
  9. the contract storage is set to 1. Contract storage variable do not need an initializer; when
  10. it is not present, it is initialized to 0, or ``false`` if it is a ``bool``.
  11. Immutable Variables
  12. ___________________
  13. A variable can be declared `immutable`. This means that it may only be modified in a constructor,
  14. and not in any other function or modifier.
  15. .. include:: ../examples/contract_storage_immutable.sol
  16. :code: solidity
  17. This is purely a compiler syntax feature, the generated code is exactly the same.
  18. Accessor Functions
  19. __________________
  20. Any contract storage variable which is declared public, automatically gets an accessor function. This
  21. function has the same name as the variable name. So, in the example above, the value of counter can
  22. retrieved by calling a function called ``counter``, which returns ``uint``.
  23. If the type is either an array or a mapping, the key or array indices become arguments to the accessor
  24. function.
  25. .. include:: ../examples/contract_storage_accessor.sol
  26. :code: solidity
  27. The accessor function may override a method on a base contract by specifying ``override``. The base function
  28. must be virtual and have the same signature as the accessor. The ``override`` keyword only affects the
  29. accessor function, so it can only be used in combination with public variables and cannot be used to
  30. override a variable in the base contract.
  31. .. include:: ../examples/contract_storage_accessor_override.sol
  32. :code: solidity
  33. How to clear Contract Storage
  34. _____________________________
  35. Any contract storage variable can have its underlying contract storage cleared with the ``delete``
  36. operator. This can be done on any type; a simple integer, an array element, or the entire
  37. array itself. Contract storage has to be cleared slot (i.e. primitive) at a time, so if there are
  38. many primitives, this can be costly.
  39. .. include:: ../examples/contract_storage_clear.sol
  40. :code: solidity