Welcome back to our Solidity series! Today, we're diving deeper into the world of variables and data types. Think of variables as containers where you store different types of data, much like various bins in a workshop, each designed to hold specific tools or materials. In Solidity, these "bins" are strictly labeled because the language needs to understand what's inside to operate efficiently. Let's explore these containers and see how you can utilize them in your smart contracts.
What Are Variables?
Variables in Solidity are placeholders used to store data. They can hold values such as numbers, texts, or more complex structures. Declaring a variable is like declaring what type of data you expect to store in your bin and then naming it.
Data Types
Solidity provides various data types to cater to the needs of your program. Let's examine the foundational types and then move on to more complex structures.
uint8, uint16, uint32, all the way up to uint256, with the default being uint256, meaning that if you do not provide the type, it will be automatically will be uint256 (uint -> uint256). Each step increases the maximum number it can store.uint8 smallNumber = 255;
uint largeNumber = 123456789;
uint, int also comes in various sizes from int8 to int256.int mediumNumber = -12345;
int256 bigNumber = -123456789012345;
bool isRegistered = true;
address userAddress = 0xAb390...;
string name = "Alice";
bytes1 to bytes32. There's also a dynamic bytes type for arbitrary-length data.bytes32 hash = "abc123...";
bytes memory data = "Dynamic length bytes";
struct Person {
string name;
uint age;
}
Person public alice = Person("Alice", 30);
enum State { Waiting, Ready, Active }
State public currentState = State.Waiting;
Declaring Variables
Here's how you to declare these variables in a Solidity contract:
pragma solidity ^0.8.0;
contract MyContract {
uint public count = 10;
bool private isActive = false;
address public ownerAddress;
string private greeting = "Hello";
struct Book {
string title;
string author;
uint year;
}
Book public book;
enum Phase { Init, Running, Stopped }
Phase public currentPhase = Phase.Init;
function setBook(string memory *title, string memory* author, uint \_year) public {
book = Book(\_title, *author,* year);
}
function changePhase(Phase \_newPhase) public {
currentPhase = \_newPhase;
}
}
Do not worry about the functions. Just focus on how the book and currentPhase is created in the functions. We will focus more on functions later in the course.
Swap insights and ask questions about “Learn everything about Scroll”.
Ask a question or share your thoughts about this lesson.