Exporting Identifiers
In Go, an identifier is exported from a package when its name starts with an uppercase letter. Any identifier starting with an uppercase letter is accessible outside the package, whereas those beginning with a lowercase letter (or an underscore) are confined to the current package. For example, consider the following code in the “encrypt” package:When exporting identifiers, document each exported element thoroughly. This practice ensures that the package API remains robust and backward compatible unless a major version change occurs.
Importing Packages to Access Exported Identifiers
To use exported constants, variables, or functions from another package, include an import statement in your code. For instance, if you want your main program to use the Nimbus function from the “encrypt” package, your code might appear as follows:Creating and Using a Decrypt Package
To complement the encryption functionality, you can create a “decrypt” package. First, create a file namedalgorithm.go in the decrypt package directory with a decryption algorithm that reverses the encryption by subtracting three from each character’s ASCII code:
Importing Packages from a Different Module Locally
At times, you might need to import a package from another module that hasn’t yet been published to a version control system. Consider a scenario where you have another module called “learn” that uses the encryption algorithm from your cryptit module. In the main file of the learn module, you might include:go mod tidy may produce an error like this:
replace directive in your go.mod file. Execute the following command:
go.mod might look like:
go mod tidy and then executing your main file should result in:
The replace directive modifies the module path entirely; it cannot replace only a specific package within the module.
Summary
In this article, you learned the following:- Export identifiers in Go by capitalizing the first letter so that they are accessible outside the package.
- Use the import statement to access exported identifiers from other packages.
- Import packages within the same module by referencing the appropriate module path.
- For local modules that are not yet published, utilize the replace directive in the
go.modfile to redirect the module path to your local directory.