Recently, I have been revisiting Solidity, consolidating the finer details, and writing "WTF Solidity" tutorials for newbies.
Twitter: @0xAA_Science | @WTFAcademy_
Community: Discord|Wechat|Website wtf.academy
Codes and tutorials are open source on GitHub: github.com/AmazingAng/WTF-Solidity
In this lecture, we will introduce two important variable types in Solidity: array
and struct
.
Array
An array
is a variable type commonly used in Solidity to store a set of data (integers, bytes, addresses, etc.).
There are two types of arrays: fixed-sized and dynamically-sized arrays.:
- fixed-sized arrays: The length of the array is specified at the time of declaration. An
array
is declared in the formatT[k]
, whereT
is the element type andk
is the length.
- Dynamically-sized array(dynamic array): The length of the array is not specified during declaration. It uses the format of
T[]
, whereT
is the element type.
Notice: bytes
is a special case, it is a dynamic array, but you don't need to add []
to it. You can use either bytes
or bytes1[]
to declare a byte array, but not byte[]
. bytes
is recommended and consumes less gas than bytes1[]
.
Rules for creating arrays
In Solidity, there are some rules for creating arrays:
- A
memory
dynamic array, can be created with thenew
operator, but the length must be declared, and the length cannot be changed after the declaration. For example:
-
Array literal are arrays in the form of one or more expressions, and are not immediately assigned to variables; such as
[uint(1),2,3]
(the type of the first element needs to be declared, otherwise the type with the smallest storage space is used by default). -
When creating a dynamic array, you need an element-by-element assignment.
Members of Array
length
: Arrays have alength
member containing the number of elements, and the length of amemory
array is fixed after creation.push()
: Dynamic arrays have apush()
member function that adds a0
element at the end of the array.push(x)
: Dynamic arrays have apush(x)
member function, which can add anx
element at the end of the array.pop()
: Dynamic arrays have apop()
member that removes the last element of the array.
Example:

Struct
You can define new types in the form of struct
in Solidity. Elements of struct
can be primitive types or reference types. And struct
can be the element for array
or mapping
.
There are 4 ways to assign values to struct
:
Example:

Example:

Summary
In this lecture, we introduced the basic usage of array
and struct
in Solidity. In the next lecture, we will introduce the hash table in Solidity - mapping
。