Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 47 ยท Language Basics

Strings, Bytes, Arrays and Structs

Learn Solidity reference types: dynamic and fixed arrays, string versus bytes, structs, and how memory, storage and calldata copies differ.

Value types such as uint256 and bool are small and simple: when you assign one to another variable, you get a copy of the value. Reference types are different. Arrays, strings, bytes and structs can be large, so Solidity makes you say where the data lives every time you use one. That location is called the data location, and it decides whether an assignment copies the data or just points at it.

This lesson covers the four reference types you will use constantly and the copy rules that trip up almost every beginner. The deeper story of what each location costs comes later in Storage, Memory and Calldata. Here the goal is to read and write ordinary contract code without surprises.

Where does the data live?

storage Permanent contract data. Expensive to write.
memory Temporary scratch space during one call.
calldata Read-only input of an external call.

Reference-type parameters and locals must name one of these.

1 / 2

Arrays

An array holds elements of one type. A fixed-size array has its length in the type, and a dynamic array can grow:

SOLIDITY
uint256[3] public fixedScores;   // always exactly 3 elements, all start at 0
uint256[] public scores;         // starts empty, can grow

Indexes start at zero, and reading past the end is not undefined behavior as in C: the call reverts with a panic. A storage array has a length member and two helpers:

SOLIDITY
function addScore(uint256 s) external {
    scores.push(s);          // append, length grows by one
}

function removeLast() external {
    scores.pop();            // remove the last element; reverts if empty
}

function count() external view returns (uint256) {
    return scores.length;
}

Two details matter here. First, delete scores[i] does not remove the element. It resets it to the default value (zero), and the length stays the same. Second, you cannot remove an element from the middle of a storage array cheaply. The usual trick is swap and pop: copy the last element over the one you want to remove, then pop(). It changes the order, but it costs a fixed amount of gas instead of shifting everything.

Arrays created in memory are different: their length is fixed when you create them and they have no push:

SOLIDITY
function squares(uint256 n) external pure returns (uint256[] memory) {
    uint256[] memory result = new uint256[](n);
    for (uint256 i = 0; i < n; i++) {
        result[i] = i * i;
    }
    return result;
}

A public array state variable gets an automatic getter, but the getter takes an index and returns a single element. To return the whole array you write your own function, and you should be careful: a function that copies a huge array out costs gas that grows with its size.

Array slices

A slice is a window onto part of a calldata array, written x[start:end] (the end is excluded, and either side may be left out). Slices exist only for calldata arrays, so they are mostly used in external functions to pass part of the input on without copying it.

SOLIDITY
function sumRange(uint256[] calldata data, uint256 start, uint256 end)
    external
    pure
    returns (uint256 total)
{
    uint256[] calldata part = data[start:end];   // elements start ... end - 1
    for (uint256 i = 0; i < part.length; i++) {
        total += part[i];
    }
}

function firstFour(bytes calldata payload) external pure returns (bytes4) {
    return bytes4(payload[:4]);                  // a typical use: read a function selector
}

If start > end or end > data.length, the call reverts. A slice of [1, 2, 3, 4, 5] taken as [1:4] holds 2, 3, 4. You cannot slice a memory or storage array; loop with indexes instead.

Strings and bytes

A string in Solidity is dynamically sized UTF-8 text. That is all it is: there are no string methods, no .length and no indexing like name[0]. The bytes type is the same thing without the "this is text" promise, and it does support .length and indexing. Converting between them costs nothing:

SOLIDITY
string public greeting = "hello";

function greetingLength() external view returns (uint256) {
    return bytes(greeting).length;   // counts bytes, not characters
}

Because string is UTF-8, a character such as รฉ takes two bytes and an emoji takes four, so the byte length can be larger than what a human counts. Joining pieces is done with string.concat(a, b) and bytes.concat(a, b).

Comparing two strings with == is not allowed. The common way is to compare their hashes:

SOLIDITY
function sameText(string memory a, string memory b) public pure returns (bool) {
    return keccak256(bytes(a)) == keccak256(bytes(b));
}

When a value is short and fixed, such as a 4-letter code or a hash, prefer the fixed-size bytes1 to bytes32 types. They are value types, they are cheaper, and they can be compared directly. Use string for text meant to be shown to people, and keep long text off-chain, because storing it is expensive.

Structs

A struct groups related fields into your own type:

SOLIDITY
struct Player {
    string name;
    uint256 score;
    bool active;
}

Player[] public players;

There are two ways to create one:

SOLIDITY
players.push(Player("Ada", 10, true));                                  // positional
players.push(Player({name: "Grace", score: 20, active: true}));         // named

The named form is safer, because adding a field later cannot silently shift your arguments. Fields you do not mention are not allowed in the named form, so name them all. A struct can contain arrays, mappings (see Mappings) and other structs, but not itself directly. Reading a field uses a dot: players[0].score.

Memory, storage and calldata copies

The data location rules come down to a short list.

  • Function parameters and return values of reference types need a location: memory for a mutable copy, or calldata for a read-only view of the call data (only in external functions, or in public ones since 0.6.9). Prefer calldata for inputs you only read, because it avoids a copy.
  • State variables are always in storage.
  • Local variables need a location too.

Now the important part. Assigning between locations behaves like this:

SOLIDITY
Player storage p1 = players[0];   // a pointer: p1.score = 99 changes the stored player
Player memory p2 = players[0];    // a copy: p2.score = 99 changes only the copy

storage to memory copies the whole value, which also costs gas for every field it reads. A local storage variable copies nothing; it is a reference to the same slots as the original. Beginners forget the storage keyword, write memory, edit the copy, and wonder why the contract did not change. The reverse also bites: memory to storage writes the entire value into storage, and that is where the gas bill goes up.

Between two memory variables, an assignment shares the data (both names refer to the same array), unlike value types. That is the same behavior you know from JavaScript objects.

If you update a struct in storage, do it through a storage pointer or by writing the field directly, such as players[i].score += 1. Changing a memory copy never writes back by itself.

A stand-in for copy and reference behavior

Solidity code cannot run on this site, so the examples above are read-only. The two TryIts below are JavaScript stand-ins. They are not the EVM, but they model the rule that matters here: a memory copy is independent, and a storage pointer points at the original.

JS Memory copy versus storage pointer

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The copy never touched the stored player, while the pointer did. Next, a stand-in for a dynamic storage array that checks bounds like Solidity does and shows delete versus swap and pop.

JS push, pop, delete and swap-and-pop

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What is real: the rules for delete, pop, bounds checks and the copy-versus-pointer difference. What is the stand-in: JavaScript objects instead of storage slots, structuredClone instead of a real memory copy, and no gas. The panic codes in the messages (0x31 for popping an empty array, 0x32 for an out-of-bounds index) follow Solidity.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does delete scores[2] do to a storage array uint256[] scores?

    delete assigns the default value, which is 0 for uint256. The array keeps its length, so use swap and pop to actually remove an element.
  2. 2. Why can you not write name[0] for a string name?

    string is just UTF-8 bytes without helper members. Converting to bytes costs nothing and gives you .length and indexing, counted in bytes.
  3. 3. What is the difference between Player memory p = players[0]; and Player storage p = players[0];?

    A memory variable receives a copy, so editing it never changes the contract. A local storage variable is a reference to the original slots.
  4. 4. Which location is best for an external function's array parameter that you only read?

    calldata is a read-only view of the call's input, so no copy is made. Parameters of reference types must always name a location.

Summary

  • Reference types (arrays, string, bytes, structs) must name a data location: storage, memory or calldata.
  • Storage arrays support push, pop and length; delete arr[i] only zeroes an element. Use swap and pop to remove cheaply.
  • Memory arrays have a fixed length from new T[](n) and no push.
  • string has no length or indexing; use bytes(s), string.concat and hash comparison.
  • Structs group fields; prefer the named construction form.
  • Storage to memory copies, a local storage variable is a pointer, and memory to memory shares data.

Next: Mappings.