What are Libraries in Solidity?
Libraries are similar to Contracts, but are mainly intended for reuse. A Library contains functions which other contracts can call. It is very similar in a sense when we think about interfaces, except whereas interfaces are connecting contracts, but libraries are more like a storing of functional data that we can then apply to contracts. Solidity have certain restrictions on use of a Library. Following are the key characteristics of a Solidity Library.
Let's take this theorizing of what a Library is and put it into some code. To bring a library we type the keyword library and call it Search. Let's say we want search through a database. Inside the Library we can write a public view function (remember that it can be called from outside the Library).
How do we search through things? We can manually look through it, or alternatively, we can loop through something. So, in our example, we will use the For Loop. We want this loop to return the index value of some integer we are searching for. For doing this we will use an if statement:
Because our statement only has single lines, we don't need these curly brackets, we can just write it all in one line. It is nice and clean, it is fine to do like this.
Just like that, we have created our first Library. Now, let's test this Library by creating a contract with a variable and a constructor for the beginning.
领英推荐
Also we are going to make a function (isValuePresent) which will check for a value (uint val), make it external view and return a integer. What we are going to do here is we are going to create a value and we are going to set it to the input.
And then how do we actually connect the dots? How do we say: "Well, now search!". We want to search through the data and set up the data to the array uint[] data and the value to our val input. Do do that, we can directly grab our Search Library. From our Library, with dot notation, we have access to our function, so we can grab indexOf and then we go into our arguments and write data as first argument and value as second argument. Next we will return index.
Now we are ready to test if it is working. Let's deploy and have a look.
It is working fine :)
See you in the next articles about #solidity , #remix , #evm , #ethereum , #smartcontracts and other interesting topics from the #blockchain world.
Here is the link to my GitHub repository for the code from the article.