DEV Community

Eternal Dev for Eternal Dev

Posted on • Originally published at eternaldev.com on

Introduction to Golang

#go

Introduction to Golang

Learning a new language can be a daunting task but Go language looks easy to learn for both beginners and veterans. The minimalist nature of the language makes it a good candidate when starting your next project

Installation

You can install Go using the tutorial from their official websiteInstall Go

First Go program

Printing to the console is the standard first program you have to write in any language :) and so we will learn how we can do that in Go

  1. Create a new file called main.go
package main

import "fmt"

func main() {
    fmt.Println("First Go program !!")
}
Enter fullscreen mode Exit fullscreen mode

2.Declare main package at the start of the file to let Go know that all the methods in this file belongs to main package

Package is a way to group functions, and it's made up of all the files in the same directory

3.Next we are importing the fmt package which contains function to print to the console

4.Create a function called main which contains the logic to print to console. main function inside Go package is called by default when you run the package

That's it, we have a very simple go code to start.

Running Go program

Open your terminal to the folder which contains your main.go file and run the below command

go run main.go

Output: First Go program !!
Enter fullscreen mode Exit fullscreen mode

Building binary

Once you have the code defined, it is very easy to generate a binary of the program and share your beautiful "Print to the console" application to the world :)

go build main.go
Enter fullscreen mode Exit fullscreen mode

After running this command, you will have binary executable file created in the same folder with your package name main

If you are in linux environment, you can run the below command to see your console output.

./main

Output: First Go program !!
Enter fullscreen mode Exit fullscreen mode

Conclusion

Just 7 lines of Go code and we are able to build an app which can be act as Command Line Interface (CLI) tool

There are more exciting things to do with Go and we will cover more on further posts.

Stay tuned by subscribing to our mailing list and joining our Discord community

Discord

Top comments (0)