DEV Community

Cover image for Arrays & Structs.
AbhayPatel98
AbhayPatel98

Posted on

Arrays & Structs.

Solidity Reference Types

At this point, you are well on your way to becoming a Solidity master. We've looked at the primitive data types in Solidity, such as:

uint/int
boolean
address
enum
bytes

Primitive data types can also be referred to as "value types". A value type stores its data directly in the variable.

Solidity, like most other object-oriented programming languages, has another type of data for reference-based data types, such as:

arrays
strings
structs

mappings (also reference types, but we've already covered them quite heavily!)
A reference type does not store values directly in a variable. Instead, reference types hold a pointer to the address of the data's location.

Image description

The two main reference types we will cover today are: arrays and structs.

Arrays
In computer science, an array is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key. In Solidity, an array can be both of fixed or dynamic size.

What Are Dynamic & Fixed Arrays?
The size of dynamic arrays are not predefined when they are declared. As elements are systematically added, the size of the dynamic array changes, and during runtime, the actual size of the array will be determined.

In contrast, fixed arrays have a predefined size, and the quantity of elements present in the array should not exceed the size of the array.

Storage Arrays
Storage arrays are typically declared as state variables and can be either fixed or dynamic in size. Here's a Solidity code snipper declaring both a fixed and dynamic-sized array in a simple MyContract

Image description

Both fixed and dynamic sized arrays have access to the .length array member:

.length: returns how many values an array holds per index
Dynamic storage arrays have the typical array methods available, such as:

.push(): used to add an element to the array at the last position

.pop(): used to remove an element of the array at the last position

Top comments (0)