Learn how to Store data on the blockchain.
storage
in a smart contract. In this step-by-step guide, you’ll learn how to access and use the storage
data location.
SimpleStorage
.
storage
variables. Create a variable to store the age of a person and another to store the number of cars that they own. Give age
an initial value of your choosing, but don’t make an assignment for cars
;
Reveal code
uint8
for each of these. For types that are smaller than 32 bytes, multiple variables of the same type will be packed in the same storage slot. For this to work, the variables must be declared together.
constructor
function to your contract. Similar to other languages, this function is called exactly once, when the contract is deployed. The constructor may have parameters, but it does not require them.
You can use the constructor to perform various setup tasks. For example, the constructor for the ERC-721 token that is the underlying mechanism for most NFTs uses the constructor to set up the name and symbol for the token.
Create a constructor function and use it to assign the value of your choosing to cars
.
Reveal code
public
variables.
Add the public
keyword to both variables. Unlike most languages, public
goes after the type declaration. Your contract should now be similar to:
Reveal code
cars
stored.
cars
public
function that takes a uint8
for _numberOfCars
and then simply assigns that value to the state variable cars
. Because this function modifies state, it does not need pure
or view
. It isn’t either of those.
Reveal code
age
age
value. This problem has slightly different considerations. Sadly, age
will never go down. It should also probably only go up by one year for each update. The ++
operator works in Solidity, so we can use that to create a function that simply increments age when called.
Reveal code
adminSetAge
that can set the age
to a specified value.
age
or number of cars
than what you’ve hardcoded into the contract?
As mentioned above, the constructor
can take arguments and use them during deployment. Let’s refactor the contract to set the two state variables in the constructor based on provided values.
Reveal code
constructor
, you’ll have to provide them during deployment.
Reveal code