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 uintas 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.

Coinmonks

Coinmonks is a non-profit Crypto educational publication. Follow us on Twitter @coinmonks Our other project — https://coincodecap.com

)

Gustavo (Gus) Guimaraes

Written by

A curious mind, joie de vivre practitioner

Coinmonks

Coinmonks

Coinmonks is a non-profit Crypto educational publication. Follow us on Twitter @coinmonks Our other project — https://coincodecap.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade