Basics of Go to get started.

Basics of Go to get started.

·

2 min read

Why GO?

  • It is similar syntax to many other languages

  • It runs fast and uses very little memory.

  • It runs across many platforms.

  • It has simple syntax for multi-threaded programs.

  • It provides some object-oriented features.

  • It has garbage collection.

Compiling Files:

First way:

go build greet.go -> this is compiled. This builds a executable file. ./greet -> This is used to execute the file.

Second way:

go run greet.go -> The go run command compiles the code (like go build) and executes it.

Packages:

Many .go files are organized in directories called packages. (check internet) package main

import "fmt"

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

The first line is the package declaration The import statement allows us to use code or functions from other packages. Here we are using println function from fmt function.

Function:

We declare functions using the func keyword and followed by the function name. The name is followed by () and a set of curly braces{}. The body of the function is written within the curly braces.

Importing multiple packages:

Importing multiple packages can be done in two ways. One is importing packages in multiple lines. For example,

import "package1" import "package2"

Second way is by importing packages with parentheses.

import ( "package1" "package2" )

You can also provide alias name to a package and use that alias name to call a function from that package.

For example, import ( p1 "package1" "package2" )

You can use p1.funcName() instead of package1.funcName().

Comments

Comments can be used to explain the code. Comments can be of two types in Go - Line Comments and Block comments.

Line comments starts with //. And the Block comments start with / * and end with

  • /.

Looking up for a documentation in Go.

One can view official documentation about packages in Go using go doc command followed by the name of the package. For example, go doc fmt is used to view documentation about fmt package. Documentation about a function can be viewed by go doc command followed by the name of the package and a dot and function name.