Want to learn how to build better Go applications faster and easier? You can.
Check out my course on the Go Standard Library. You can check it out now for free.
Golang, or Go as it is commonly known, is a statically typed language developed by Google in 2009. It has gained significant popularity due to its simplicity and ease of use, making it a great language for beginners to learn. In this article, we will cover how to run your Go programs on the Ubuntu operating system.
To start using Go, you need to install it on your computer. You can download the binary distribution of Go from the official website and follow the installation instructions provided in the documentation.
After installing Go, you need to set up your environment variables so that the compiler and other tools can be accessed from any location on your system. To do this, open a terminal window and run the following command:
export GOPATH=$HOME/go
export GOROOT=/usr/local/go
This sets the GOPATH
variable to the go
directory in your home folder and the GOROOT
variable to the location where Go is installed. This allows you to run Go commands from any directory on your system.
To create a new project, open a terminal window and navigate to a directory where you want to store your code. Then, run the following command to create a new package:
go mod init github.com/your_username/myproject
This creates a new package with the name myproject
under the github.com/your_username
namespace.
Now that you have set up your environment and created a new project, it’s time to write your first Go program. Create a new file called main.go
in the myproject
directory and add the following code:
package main
import "fmt"
func main() {
fmt.Println("Hello, world!")
}
This is a simple Go program that prints “Hello, world!” to the console.
To compile your Go program, run the following command in the terminal:
go build myproject
This creates an executable file called myproject
under the bin
directory of your project. To run this file, you can use the following command:
./bin/myproject
This should print “Hello, world!” to the console, indicating that your program is working correctly.
In this article, we have covered how to set up your environment and create a new Go project on Ubuntu. We also wrote our first Go program and compiled it into an executable file. With these basic steps under your belt, you are now ready to start building more complex programs in Go.