Writing Go Modules is as simple as writing code in a file inside a folder. The folder is known as the module.
A module is a folder
There could be more than one
.gofiles in the module with module declaration at toppackage gomoduleAny function from any of the
.gofile inside a module can be called from any other file in the same module.File names does not matter inside a module as far as importing a module is concerned.
While importing a module, the whole of the module is imported. That means all the
.gofiles in that module is available, to call theirfunctionsfrom. The functions are called with the module name, not the file name.While declaring a module the
.modfile holds the key. It declares the URL and module name asmodule saumya.learning/gomodule. The respective.gofiles in that module, must declare the package declaration aspackage gomoduleand the URL must be a live URL.
Example of a module declaration in a .mod file
module saumya.learning/gomoduleThe .go files in that module must declare the package declaration as below.
package gomoduleJust remember that these declarations are must be the first line in the respective files.
The URL in the module declaration
saumya.learning/gomodulemust be a valid URL. Because while importing the module in another module, the Go is going to import the module from that URL. In this example, the URL issaumya.learningwhich must exist in the internet.
Well, there is a way to work with local modules. That is, importing modules from local file system. It has to be specifically declared in the .mod file as below.
replace saumya.learning/gomodule => ../2_agoIn this example, it is importing a Go Module from a folder, relative to our working folder.
The mod Command
Creation of a Go module is done with mod command.
go mod init saumya.learning/hello
Here it is creating a .mod file with module declaration as module saumya.learning/hello.
Happy Going.