A Beginner's Guide to Go

A Beginner's Guide to Go

·

7 min read

This article is intended for individuals who want to get started with Go, often known as Golang.

Google developers Robert Griesemer, Rob Pike, and Ken Thompson created Go, a statically typed, compiled language. It is well-known for its simplicity, effectiveness, and simplicity of use, making it an excellent choice for novices.

In this guide, we'll go through the fundamentals of Go. We'll begin by configuring your environment, building your first "Hello, World" program, and learning the basic structure of a Go program. We'll also go over some of the language's fundamental concepts.

Prerequisites

While some programming knowledge is advantageous, it is not required to get started with Golang. The first thing you'll need is a code editor. Several text editors provide decent Go support. Some of the most popular ones include VSCode (which is free), GoLand (which is charged), and Vim (which is also free). To run your code, you'll need a command terminal in addition to a text editor. With these tools in hand, you're ready to go on your Golang adventure!

Install Go

The first step in getting started with Go is to download and install it. You may do so by going to the official Go website. The website includes thorough instructions for downloading the Go binaries for your particular operating system (Windows, macOS, or Linux). After downloading the binaries, you may install it by following the instructions.

For example, this is how you install Go on Linux-related operating systems:

  1. Remove any previous Go installation by deleting the /usr/local/go folder (if it exists), then extract the archive you just downloaded into /usr/local, creating a fresh Go tree in /usr/local/go:

     $ rm -rf /usr/local/go && tar -C /usr/local -xzf go1.21.1.linux-amd64.tar.gz
    

    (You may need to run the command as root or through sudo).

    Do not untar the archive into an existing /usr/local/go tree. This is known to produce broken Go installations.

  2. Add /usr/local/go/bin to the PATH environment variable.

    You can do this by adding the following line to your $HOME/.profile or /etc/profile (for a system-wide installation):

     export PATH=$PATH:/usr/local/go/bin
    

    Note: Changes made to a profile file may not apply until the next time you log into your computer. To apply the changes immediately, just run the shell commands directly or execute them from the profile using a command such as source $HOME/.profile.

  3. Verify that you've installed Go by opening a command prompt and typing the following command:

     $ go version
    
  4. This should show the Go version that is currently installed. You are now ready to begin coding with Go!

Writing your first Golang program

A "Hello, World" program is the customary first program written in any language. This straightforward program will print the words "Hello, World" to the terminal. In Go, you can perform the following:

package main

import "fmt"

func main() {
    fmt.Println("Hello, World")
}

Let’s break down what’s happening in this program:

  • package main: Every Go program starts with a package declaration. Packages are Go’s way of organizing and reusing code. There are two types of Go programs: executable and reusable. The main package is special. It defines a standalone executable program, not a library.

  • import "fmt": This includes the fmt package in our program. fmt stands for format, and it has functions for formatting and printing output.

  • func main(): main is a special function in Go. The main function is the entry point of our executable program. When you run the program, it executes the main function.

  • fmt.Println("Hello, World"): This is a function call from the fmt package. Println is a standard library function that prints to the console and adds a newline character at the end.

You can run this program by saving it to a file with a .go extension (for example, hello.go), and then from your terminal, navigate to the directory containing your file and type go run hello.go. You should see Hello, World printed to your console. Congratulations, you’ve just written and run your first Go program!

Go Package Discovery Tool

As you learn more about Go programming, you'll discover that it has a thriving ecosystem of packages that you may utilize in your code. By offering pre-written code for common tasks, these packages can save you time and effort.

The Go Package Discovery Tool is a useful tool for locating these packages. It's an online tool for searching for Go packages based on their usefulness. For example, if you're searching for a package to assist with online scraping, put "web scraping" into the search field, and the tool will return a list of web scraping-related packages.

To utilize a package in your code, you must import it at the start of your file. If you wanted to utilize the fmt package, for example, you would put import "fmt" at the start of your file. The fmt package's functions can then be used in your code.

Remember that, while packages can be quite useful, it's also critical to understand how they function. Before using a package, read the documentation and make sure you understand what it does. This will allow you to use the product more successfully and avoid any problems down the road.

Creating a Go Module

A module in Go is a grouping of related Go packages that are released together. A Go module is specified via a go.mod file at the root of the source directory tree for the module.

In this lesson, we will build two modules. The first module will be a library that other libraries or apps can import. The second module will consist of an application that makes use of the library module.

  1. Creating a Library Module:

    • Create a new directory for your module and navigate into it.

    • Initialize a new module with go mod init <module-name>. This will create a new go.mod file in your directory.

    • Create a new .go file in the directory. This file will contain the code for your library.

    • Write your library code in the .go file. Make sure to declare all the functions that you want to be accessible from other modules with an uppercase first letter.

  2. Creating an Application Module

    • Create a new directory for your application module and navigate into it.

    • Initialize a new module with go mod init <module-name>.

    • Create a new .go file in the directory. This file will contain the code for your application.

    • In your application code, import your library module with import "<module-name>". You can now use the exported functions from your library in your application code.

Remember, the power of modules comes from the ability to reuse and share code. Always think about how you can make your code modular and reusable.

Calling Functions from Modules

External Modules:

The support for modules in Go allows you to use code produced and shared by others. This can save you time and effort while also allowing you to tap into the collective wisdom of the Go community.

To utilize an external module, you must first include it in your project. In your terminal, use the go get command to do this. To utilize the popular gin-gonic/gin package for developing HTTP request routers, for example, enter go get -u github.com/gin-gonic/gin .

After adding the external module to your project, you may import it in your Go files as follows:

import (
    "github.com/gin-gonic/gin"    
)

Now, you can use the functions from the gin-gonic/gin module in your code. For example, you can create a new router like this:

router := gin.Default()

This line of code calls the Default function from the gin-gonic/gin module and assigns the result to the variable router.

Importing your own Module Functions:

Similarly, you can also import and use functions from your own modules. Suppose you have a module named mymodule and inside it, you have a package named mypackage which has a function named MyFunction. You can use it in another package like this:

import (
    "mymodule/mypackage"
)

func main() {
    mypackage.MyFunction()
}

Remember, when you’re using external modules or your own modules, it’s important to understand what the functions you’re using do. Always read the documentation for the module to ensure you’re using it correctly.

Conclusion

And that’s a wrap! We’ve covered the basics of getting started with Golang, from setting up your environment to writing your first program and understanding the power of modules. Remember, the journey of learning a new language is a marathon, not a sprint. It’s okay to not understand everything at once. Take your time, practice, and don’t hesitate to seek help when you need it.

As you continue to explore Golang, you’ll discover its power and flexibility. Whether you’re building a web service, designing a complex system, or just writing scripts for automation, Golang has got you covered.

We hope this guide has helped get you started with Golang. Follow for more articles like this! Thanks for reading!