using.rst 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. ``Using`` directive
  2. ===================
  3. Binding methods to types with ``using``
  4. ---------------------------------------
  5. Methods can be bound to builtin types and any user-defined types like structs
  6. using the ``using`` syntax. This can be done either using libraries or free
  7. standing functions.
  8. ``using`` with free standing functions
  9. ______________________________________
  10. First, declare a function with one or more arguments. Once the function
  11. is bound with ``using``, it can be called like a method.
  12. .. include:: ../examples/using.sol
  13. :code: solidity
  14. The ``using`` declaration can be done on file scope. In this case, the type must
  15. be specified in place of ``*``. The first argument must match the type that is
  16. be used in the ``using`` declaration.
  17. If a user-defined type is used, the the ``global`` keyword can be used. This
  18. means the ``using`` binding can be used in any file, even when the type is
  19. imported.
  20. .. include:: ../examples/using_global.sol
  21. :code: solidity
  22. Now even when ``User`` is imported, the clear_count() method can be used.
  23. .. include:: ../examples/using_imports.sol
  24. :code: solidity
  25. ``using`` with libraries
  26. ________________________
  27. A library may be used for handling methods on a type. First, declare a library
  28. with all the methods you want for a type, and then bind the library to the type
  29. with ``using``.
  30. .. code-block:: solidity
  31. struct User {
  32. string name;
  33. uint name;
  34. }
  35. library UserLibrary {
  36. function clear_count(User user) internal {
  37. user.count = 0;
  38. }
  39. function inc(User user) internal {
  40. user.count++;
  41. }
  42. function dec(User user) internal {
  43. require(user.count > 0);
  44. user.count--;
  45. }
  46. }
  47. using UserLibrary for User global;
  48. Scope for ``using``
  49. ___________________
  50. The ``using`` declaration may be scoped in various ways:
  51. - Globally by adding the ``global`` keyword. This means the methods are available
  52. in any file.
  53. - Per file, by omitting the ``global`` keyword
  54. - Per contract, by putting the ``using`` declaration in a contract definition
  55. If the scope is per contract, then the type maybe be replaced with ``*`` and
  56. the type from the first argument of the function will be used.