- How exports are determined in Go
- How to import packages inside the same module
- How to import a local module from a different module using
go modreplace
Exporting in Go
Go determines visibility by the identifier’s first character—there is no explicitexport keyword.
Example: an exported function in package
encrypt
Nimbus to nimbus, it becomes unexported and cannot be accessed from another package.
Keep in mind:
Anything you export becomes part of your package’s public API. Document exported identifiers and maintain backward compatibility unless you intentionally make a major version change.
Importing packages
To use exported constants, variables, types, or functions from another package, add an import for that package. Without the import, Go code outside the package cannot access its exported identifiers.Importing packages within the same module
Assume the module path isgithub.com/Priyanka-yadavv/cryptit and the encrypt package is in ./encrypt. From main you can call encrypt.Nimbus like this:
Adding a decrypt package
Create adecrypt package (for example ./decrypt/algorithm.go) that reverses the encryption:
main (same module):
Importing a local module from a different module
If you have two separate modules locally (for example,cryptit and learn) and try to import github.com/Priyanka-yadavv/cryptit/encrypt from learn before publishing cryptit to a VCS, go mod tidy (or go build) will attempt to resolve the module from the network and may report that the module exists but does not contain the requested package. Example error (illustrative):
Using go.mod replace for local development
During local development you can direct the consumer module to use a local copy of your module using thereplace directive in the consumer’s go.mod. From the learn module directory run:
learn’s go.mod will include an entry like:
learn can import github.com/Priyanka-yadavv/cryptit/encrypt and Go will use the local ../cryptit directory. Example main.go in learn:
go run main.go should print a UUID and then the encrypted string, using your local cryptit module code.
Notes about replace
- The
replacedirective substitutes a module path with another module path or a local directory. It works at the module level, not at the individual package path level, so point the right-hand side to the module root directory. - Use
replaceonly for development. When you publish the module to a VCS (for example, GitHub) and tag versions, consumers should import the published module and thereplacedirective is not necessary.
Links and references
That covers Go’s capitalization-based exports, importing packages inside the same module, and usinggo mod replace to work with local modules during development.