structs.sol 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // ethereum solc wants his pragma
  2. pragma abicoder v2;
  3. contract structs {
  4. enum enum_bar { bar1, bar2, bar3, bar4 }
  5. struct struct_foo {
  6. enum_bar f1;
  7. bytes f2;
  8. int64 f3;
  9. bytes3 f4;
  10. string f5;
  11. inner_foo f6;
  12. }
  13. struct inner_foo {
  14. bool in1;
  15. string in2;
  16. }
  17. struct_foo foo1;
  18. struct_foo foo2;
  19. // function for setting the in2 field in either contract storage or memory
  20. function set_storage_in2(struct_foo storage f, string memory v) internal {
  21. f.f6.in2 = v;
  22. }
  23. // A memory struct is passed by memory reference (pointer)
  24. function set_in2(struct_foo memory f, string memory v) pure internal {
  25. f.f6.in2 = v;
  26. }
  27. function get_both_foos() public view returns (struct_foo memory, struct_foo memory) {
  28. return (foo1, foo2);
  29. }
  30. function get_foo(bool first) public view returns (struct_foo memory) {
  31. struct_foo storage f;
  32. if (first) {
  33. f = foo1;
  34. } else {
  35. f = foo2;
  36. }
  37. return f;
  38. }
  39. function set_foo2(struct_foo f, string v) public {
  40. set_in2(f, v);
  41. foo2 = f;
  42. }
  43. function pass_foo2(struct_foo f, string v) public pure returns (struct_foo) {
  44. set_in2(f, v);
  45. return f;
  46. }
  47. function set_foo1() public {
  48. foo1.f1 = enum_bar.bar2;
  49. foo1.f2 = "Don't count your chickens before they hatch";
  50. foo1.f3 = -102;
  51. foo1.f4 = hex"edaeda";
  52. foo1.f5 = "You can't have your cake and eat it too";
  53. foo1.f6.in1 = true;
  54. set_storage_in2(foo1, 'There are other fish in the sea');
  55. }
  56. function delete_foo(bool first) public {
  57. struct_foo storage f;
  58. if (first) {
  59. f = foo1;
  60. } else {
  61. f = foo2;
  62. }
  63. delete f;
  64. }
  65. function struct_literal() public {
  66. // declare a struct literal with fields. There is an
  67. // inner struct literal which uses positions
  68. struct_foo literal = struct_foo({
  69. f1: enum_bar.bar4,
  70. f2: "Supercalifragilisticexpialidocious",
  71. f3: 0xeffedead1234,
  72. f4: unicode'€',
  73. f5: "Antidisestablishmentarianism",
  74. f6: inner_foo(true, "Pseudopseudohypoparathyroidism")
  75. });
  76. // a literal is just a regular memory struct which can be modified
  77. literal.f3 = 0xfd9f;
  78. // now assign it to a storage variable; it will be copied to contract storage
  79. foo1 = literal;
  80. }
  81. }