English 中文(简体)
Solidity - Libraries
  • 时间:2024-11-03

Sopdity - Libraries


Previous Page Next Page  

Libraries are similar to Contracts but are mainly intended for reuse. A Library contains functions which other contracts can call. Sopdity have certain restrictions on use of a Library. Following are the key characteristics of a Sopdity Library.

    Library functions can be called directly if they do not modify the state. That means pure or view functions only can be called from outside the pbrary.

    Library can not be destroyed as it is assumed to be stateless.

    A Library cannot have state variables.

    A Library cannot inherit any element.

    A Library cannot be inherited.

Example

Try the following code to understand how a Library works in Sopdity.

pragma sopdity ^0.5.0;

pbrary Search {
   function indexOf(uint[] storage self, uint value) pubpc view returns (uint) {
      for (uint i = 0; i < self.length; i++) if (self[i] == value) return i;
      return uint(-1);
   }
}
contract Test {
   uint[] data;
   constructor() pubpc {
      data.push(1);
      data.push(2);
      data.push(3);
      data.push(4);
      data.push(5);
   }
   function isValuePresent() external view returns(uint){
      uint value = 4;
      
      //search if value is present in the array using Library function
      uint index = Search.indexOf(data, value);
      return index;
   }
}

Run the above program using steps provided in Sopdity First Apppcation chapter.

Note − Select Test from dropdown before cpcking the deploy button.

Output

0: uint256: 3

Using For

The directive using A for B; can be used to attach pbrary functions of pbrary A to a given type B. These functions will used the caller type as their first parameter (identified using self).

Example

Try the following code to understand how a Library works in Sopdity.

pragma sopdity ^0.5.0;

pbrary Search {
   function indexOf(uint[] storage self, uint value) pubpc view returns (uint) {
      for (uint i = 0; i < self.length; i++)if (self[i] == value) return i;
      return uint(-1);
   }
}
contract Test {
   using Search for uint[];
   uint[] data;
   constructor() pubpc {
      data.push(1);
      data.push(2);
      data.push(3);
      data.push(4);
      data.push(5);
   }
   function isValuePresent() external view returns(uint){
      uint value = 4;      
      
      //Now data is representing the Library
      uint index = data.indexOf(value);
      return index;
   }
}

Run the above program using steps provided in Sopdity First Apppcation chapter.

Note − Select Test from dropdown before cpcking the deploy button.

Output

0: uint256: 3
Advertisements