Logo

Functions in Solidity

Learn how to write (update) and read (view) state variables through functions.

In Solidity, you use functions to either write to the blockchain (which requires sending a transaction) or read from the blockchain (which is free). Understanding how to define and call these functions is essential to creating interactive contracts.

Topics Covered:

  • State variables and why writing them costs gas
  • Functions that update state (requires sending a transaction)
  • View functions that read state (no transaction needed)

Declaring a Write Function:

A write function modifies the contract`'`s state variable, incurring a gas fee. It can look like this:

function setMyString(string memory _myString) public {
    myString = _myString;
}

Calling setMyNumber changes the on-chain value of myNumber, requiring a transaction that costs gas.

Declaring a View Function:

A view function returns data without modifying the blockchain. It’s free to call:

function getMyString() public view returns (string memory) {
    return myString;
}

Because this function does not change any state, no transaction fee is charged.

Challenge

Challenge: Complete the 'FunctionsExample' contract by doing the following: 1. Declare a state variable of type 'uint' or 'uint256'. 2. Create a function that updates the state variable using a parameter. 3. Create a view function that returns the current value of the state variable.