In this lesson, you will:
Solidity supports a range of basic data types, including booleans, integers (both signed and unsigned), fixed-length byte arrays, address types, and function types. Note that the address type varies between Ethereum Virtual Machine (EVM) and Solana. You can also create fixed-length arrays with a set size.
Here's a rundown of the primary data types in Solidity:
Note: It's best to use int64, int32, uint64, or uint32 types when working with integers.
byte
is an alias for bytes1
.
Initialize these arrays with a hex string (e.g. hex"414243"), a text string ("ABC"), or a hex value (0x414243).bytes4 foo = "ABCD";
bytes4 bar = hex"41_42_43_44";
Address Types:
address payable
can be used as a cast.Fixed-Length Arrays: Created with [length]
after the type name. They can contain any data type, including other arrays.
Function Types: Refer to functions and come in two flavours: internal and external. Internal functions are within the same contract or its base contracts. External functions reference public or external functions on any contract. Function types specify parameter types, return types, and mutability.
contract ft {
function test() public {
// reference to an internal function with two argments, returning bool
// with the default mutability (i.e. cannot be payable)
function(int32, bool) internal returns (bool) x;
// the local function func1 can be assigned to this type; mutability
// can be more restrictive than the type.
x = func1;
// now you can call func1 via the x
bool res = x(102, false);
// reference to an internal function with no return values, must be pure
function(int32, bool) internal pure y;
// Does not compile:
// Wrong number of return types and mutability is not compatible
// y = func1;
}
function func1(int32 arg, bool arg2) internal view returns (bool) {
return false;
}
}
External function types store both the contract address and function selector. Assigning to external function types requires specifying the contract and function.
contract ft {
function test(address p) external {
paffling.set_callback{ program_id: p } (this.callback);
}
function callback(int32 count, string foo) public {
// ...
}
}
contract paffling {
function(int32, string) external internal callback;
function set_callback(function(int32, string) external c) public {
callback = c;
}
function piffle() public {
callback{ accounts: [] } (1, "paffled");
}
}
On Solana, for calls from variables of external function types, you must use the accounts
call argument. The compiler can't automatically determine the required accounts, so you need to manually specify them.
function test(function(int32, string) external myFunc) public {
myFunc{accounts: []}(24, "accounts");
}
In the next lesson, we will explore constructors in Solidity, furthering your understanding of how to structure and initialize Solidity contracts.