Solidity’s ‘using’ keyword
There comes a time when one wonders the meaning behind certain features in the programming language one enjoys coding with. Lukas Cremer, Gerard and I are blockchain developers based in Berlin, Germany, and we challenged ourselves whether we could explain the use of solidity’s using
keyword.
using
is used for including a library within a contract in solidity. Check this following example:
pragma solidity ^0.4.15;library SomeLibrary { function add(uint self, uint b) returns (uint) {
return self+b;
}
}contract SomeContract {
using SomeLibrary for uint;
function add3(uint number) returns (uint) {
return number.add(3);
}
}
The code using SomeLibrary for uint;
allows us in this example to use return number.add(3);
inside the function add3
. It is basically syntactic sugar for the following:
pragma solidity ^0.4.15;library SomeLibrary {function add(uint self, uint b) returns (uint) {
return self+b;
}
}contract SomeContract {
function add3(uint number) returns (uint) {
return SomeLibrary.add(number, 3);
}
}
As we can see, by adding the keyword using
we could give any uint
within the SomeContract
the libraries functions and pass the uint
as the first parameter of that function.
Now let’s look at another example:
pragma solidity ^0.4.15;library SomeOtherLibrary { function add(uint self, uint b) returns (uint) {
return self+b;
} function checkCondition(bool value) returns (bool) {
return value;
}}contract SomeContract {
using SomeOtherLibrary for *;function add3(uint number) returns (uint) {
return number.add(3);
}
function checkForTruthy(bool checker) returns (bool) {
return checker.checkCondition();
}
}
Here the *
allows for any type from the SomeOtherLibrary
to be accessed in the contract.
Another thing we realized is that this also works for array
and struct
types but one needs to declare the storage
keyword. But this is a topic for another blog post.
Thanks to Lukas Cremer and Gerard Baecker for helping with this blog post.