Writing Our First Program
Explore how to create your first Go program by defining a main package and main function. Understand the role of packages and imports for accessing standard and external libraries. This lesson guides you in writing autonomous Go applications and organizing code effectively.
We'll cover the following...
Hello World!
The following is the Go version of the Hello World! program. Let’s name the following code hw.go and try it:
Each Go source code begins with a package declaration. In this case, the name of the package is main, which has a special meaning in Go. The import keyword allows us to include functionality from existing packages. In our case, we only need some of the functionality of the fmt package that belongs to the standard Go library. Packages that are not part of the standard Go library are imported using their full internet path. The next important thing when we’re creating an executable application is the main() function. Go considers this the entry point to the application and begins the execution of the application with the code found in the main() function of the main package.
The hw.go Go program runs on its own. Two characteristics make hw.go an autonomous source file that can generate an executable binary: the name of the package, which should be main, and the presence of the main() function.
Introducing functions
Each Go function definition begins with the func keyword followed by its name, signature, and implementation. With the main package, we can name our functions anything we want—there is a global Go rule that also applies to function and variable names and is valid for all packages except main.
Note: Everything that begins with a lowercase letter is considered private and is only accessible in the current package. The only exception to this rule is package names, which can begin with either lowercase or uppercase letters. Having said that, we are not aware of a Go package that begins with an uppercase letter!
You might now ask how functions are organized and delivered. Well, the answer is in packages.
Introducing packages
Go programs are organized in packages—even the smallest Go program should be delivered as a package. The package keyword helps us define the name of a new package, which can be anything we want with just one exception: if we’re creating an executable application and not just a package that will be shared by other applications or packages, we should name our package main.
The import keyword is used for importing other Go packages in our Go programs in order to use some or all of their functionality. A Go package can either be a part of the rich Standard Go library or come from an external source. Packages of the standard Go library are imported by name (os) without the need for a hostname and a path, whereas external packages are imported using their full internet paths, like github.com/spf13/cobra.