Using keyword in Solidity
Using keyword in Solidity.
I was recently asked to explain the meaning of the term “Using for” in Solidity. As I tried to provide a clear explanation, I realized that it can be a complex topic to understand. Therefore, I am here to attempt to clarify it further.
Using
is used to include a library within a contract in solidity.
Library
A library in Solidity is a standalone entity that is similar to a contract but is not a contract. It contains view-only functions that can be called by other contracts thereby helping to seperate and re-use code logic.
1 | library Math{ |
The library above takes 2 inputs of type uint and returns the smallest of both numbers.
Let us create a function and use the library in it.
1 | //contract to get the minimum of two numbers |
This is the standard implementation of libraries but we can make it shorter and better to enhance data types.
Using SomeLibrary for SomeDataType
1 | //contract to get the minimum of two numbers |
By using the using Math for uint
keyword in this Solidity contract, we can assign all the functions in the Math library to the uint data type. This allows us to call the functions from the library directly on the uint type within the contract, without having to explicitly reference the library.
In this way, we can use expressions like a.add(b)
within a function in the contract, where a
and b
are uint variables. Essentially, using using Math for uint
is a convenient way of writing Math.add(a,b)
in the contract code.
Using SomeLibrary for * (All Data Types)
1 | library MathBool { |
The line using MathBool for *
is a Solidity keyword that imports and makes all functions in the MathBool library available for use within the Example contract on all data types.
The for *
part in using MathBool for *
indicates that all functions in the MathBool library can be called on any data type. This means that the functions are not limited to a specific data type, unlike before when we specified a particular type, such as “for uint256”. With the for *
syntax, all types in the Example contract can use the functions defined in the MathBool library.