This section describes the use of import, which are often found in Solidity code.
import means "importing external file"
You can import external files into the current code by writing import statements.
This allows variables/functions defined in external files to be handled in the code.
How to write import
The following is how to write the import statement.
import "folder path/file name to import.sol";
An example of an actual description is shown below.
import "./sample.sol";
As a supplement, "folder path" and "file name to import" are described below.
In addition, "inheritance" is required to handle variables/functions in the imported file, which is also described here.
about folder path
The folder path is "the location to where the file is located".
The following is an example of an actual description with illustrations.
As shown above, for a file in the same hierarchy as the current code, "./filename.sol".
As shown above, if the file is one level up, it is "../filename.sol" if the file is two levels up, or "../../filename.sol" if the file is two levels up, as shown in the figure above.
As shown above, if the file is in the lower level of the hierarchy, it will be "./foldername/filename.sol".
As shown above, if the file is in a folder one level up, it will be "../foldername/filename.sol".
There are many other cases, but basically, the above can be applied.
about file name to import
Basically, you will probably import files that you have created yourself, but you can also import libraries (external files) such as openzeppelin.
An actual example is shown below.
import "@openzeppelin/contracts/utils/Strings.sol";
This allows you to use the library's convenience methods.
about inheritance
To call variables/functions in an imported file, it is not enough to simply import the file.
It is also necessary to "inherit" the contract in the imported file.
The following is how to write inheritance.
contract current contract is contract you want to import {
}
If the current contract is "TestContract" and the contract to be imported (the contract with variables/functions to be imported) is "Sample", an example description is shown below.
contract TestContract is Sample {
}
If you would like to see the full code as well as the inheritance, see "Sample Code" in the next section.
Sample Code
If the amount of code or contracts to be written becomes large, it is necessary to split the files into separate files. In such cases, the import statement is used to import those files (contracts). This is a must-use item, so be sure to keep it in mind.