Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 15, 2022 01:51 pm GMT

Anatomy of a Go Program

I recently started learning Go after going through a lot of articles talking about all the awesome features it has. Here, I will try to break down a simple Go program that prints a line to understand the anatomy of a Go program.

package mainimport "fmt"func main(){    fmt.Println("Hi there!")}

First, let's understand how to run this program. The simple command below will run the program(Assuming the file is named main.go).

go run main.go

The Go CLI has a lot of other options as well. Let's just have a look at a few frequently used ones.

CommandFunction
go buildCompiles go source code
go runCompiles and executes the go source code
go fmtFormats all code in the current directory
go installCompiles and installs a package
go getDownloads source code of other package
go testRun test cases associated with the project

Go Packages

So, lets start with package main.

A package is a collection of common source code files. A package can have many related files. The only requirement is that every file should declare the package it belongs to in the first line.

But, why to call our package main?

There are 2 types of packages in Go, they are

  1. Executable - Generates a executable file
  2. Reusable - Generates Libraries, reusable code

The name of the package main makes it an executable package. If we had used any other name, it wouldn't have been an executable package. An executable package automatically executes the main function inside it. main here is a key word. Main package should have a main function. Also, if we build other packages, it wouldn't result in a executable file.

Import

Now, let's look at import "fmt"

import is used to make the functionality available in the library package to the current program we are executing.

fmt is a standard library package available with Go. It implements formatted I/O functions similar to C's printf and scanf.

We can get a list of all the packages available in Go at (https://pkg.go.dev/std).

Go Functions

Functions are declared with the key word func. The syntax is as follows,

func <name of function> (<comma seperated arguments>) {    <body of the function>}

Structure of a Go program

All Go files follow the same pattern.

  • Package Declaration
  • Import statements
  • Function definitions

Along this article, I hope you got a grip on the basics of Go. I will write a few more articles and will get into Go routines and all the powerful features in Go. Happy Coding!


Original Link: https://dev.to/vigneshm243/anatomy-of-a-go-program-18m6

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To