DEV Community

Cover image for Everything you need to know about Go-Lang - #1
GeekTech
GeekTech

Posted on • Originally published at geektech.codes

Everything you need to know about Go-Lang - #1

You probably have heard about Google's cool language called Golang. Golang is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson. It is similar to C/C++, but with memory safety, garbage collection, structural typing, and CSP-style concurrency.

History of Golang

Go was developed by Google in 2007 to improve programming productivity. The developers wanted to amending the limitations of languages in that era while keeping the useful features like,

  • static typing and run-time efficiency
  • readability and usability
  • high-performance networking and multiprocessing.

The developers of Golang had shared dislikes for the language C++, which is also said to be the primary motivation behind this project. Announced in 2009, the version 1.0 was not released until 2012. Go is widely used in google and by open source developers. Go 1 guarantees compatibility for the language specification and major parts of the standard library. All versions up to the current Go 1.17 release have maintained this promise.
Each major Go release is supported until there are two newer major releases.

Design

Go is based on C, with an emphasis on greater simplicity and safety. The language has a syntax and environment adopting patterns more common in dynamic languages:

  • Optional concise variable declaration and initialization through type inference.

  • Fast compilation.

  • Remote package management with online package documentation.

Golang takes an distinctive approach towards a particular problem :

  • Built-in concurrency primitives: light-weight processes, channels, and the select statement.

  • An interface system in place of virtual inheritance, and type embedding instead of non-virtual inheritance.

  • A toolchain that, by default, produces statically linked native binaries without external dependencies.

The languages was tried to be kept as simple as possible, which in the process had to eliminate some common features found in other programming languages, but Golang makes up for those, by alternating features or other approaches.

Getting Started with Go

So before we dive into the programming part first we need to install Golang in your pc. You can get Go from their official download website. Download the latest version for your os.

Now that we have Golang, we need to find a proper text editor. Now for the basics part or for the learning part you can use the Go Official PlayGround, or else you might wanna use any among these : LiteIDE, Atom with Go-Plus, VSCode, or GoLand.

Now that we have both Go and a text editor with us, we might begin our journey through go.

Hello World

So let's now write our first hello world program. Now every go program starts with a package. A package is collection of source codes which are complied together. Among all the package there must be atleast one package named main. Since, we are getting started with Golang, we shall have only one package as of now. After defining our own package now we need to import another package. Now this might sound confusing but trust me when you will do the practical work it will all be a piece of cake. So where was I ? Oh yes, we would now have to import another package. This package is the fmt package which stands for format. This package contains vital functions for printing, scanning in certain formats. So we have different ways of importing package. Since we are importing one package we shall use this syntax:

import "fmt" 
Enter fullscreen mode Exit fullscreen mode

When there are multiple packages to import we shall use this syntax:
(suppose we are importing math along with fmt)

import (

"fmt"

"math"

)
Enter fullscreen mode Exit fullscreen mode

So now that we have learned how to import now let's write the main function. So let's ask the basics first. What is the main function ? In simple terms it is the block from which the complier starts executing your program, one project must have atleast one main function. So how do we define functions now ?
Well after import we define functions like this:

package main

import (

"fmt"

"math"

)

func main(){

} 
Enter fullscreen mode Exit fullscreen mode

Please note it is a syntax error if we change the way braces are put. The opening brace must be on the same line as the defination of the function and the closing brace on the next line where the function is suppose to end. We shall learn more about other functions later into the series.

Now that we have define our main functions now let's write some command to make it work. Since printing hello world, is believed to be the basics of a solid foundation, we shall print hello world as our first program. So to print we shall use the Println function from the fmt package.

fmt.println()
Enter fullscreen mode Exit fullscreen mode

To print a word or sentence we shall write it inside the parenthesis with single or double quotes on it. To do any mathematical operations, we shall not provide any quotes.

package main

import "fmt"

func main(){
fmt.Println("Hello World!")
} 
Enter fullscreen mode Exit fullscreen mode

Now that we wrote our first program let's analyse what we've written. So as said first we declared our main package, then we've imported the fmt package, we have removed the math package as we are not using it now. Keeping unused package, variables or functions generated error. Then we have declared our main function which is the entry point of every program. Inside our main function we have used the Println function from the fmt package to print hello world. Now the Println function prints and sends the cursor to the next line. If you have other print statement and you don't want it to go to the next line us Print instead of Println. Now according to our analysis our program must print Hello World. If u are using a text editor, make sure to save your file, open up terminal, navigate to the folder in which your source code is saved and type in

go run sourcecodefilename.go
Enter fullscreen mode Exit fullscreen mode

Before running this command make sure to save your file as a .go file

Output :

Hello World
Enter fullscreen mode Exit fullscreen mode

Try it Yourself

Now that you have printed hello world try printing these:

  • Your name and your profession in same line using two different statements. (Hint : Use two print statement)

  • Your name and your profession in different line.

  • The value of : 6 .0/ 2.0 (2.0*3.0)

Variables

Now that you know how to print statements let's try storing data. Now variables are like a container that stores data which might change in the future. Variables can store numbers, sentences, characters, arrays, objects, etc.

Let's learn how to declare a variable. Variable declaration is simple. We need to use the var keyword, followed by a name. This name can be anything from an alphabet to a word. We cannot use numbers, or special symbols as variable names, to store data. Given below is an example of how to declare a variable and store values to it.

var a = 10
var decimal = 45.6
var Word = "Hello World"
Enter fullscreen mode Exit fullscreen mode

Now that we know how to declare a variable and initialize it let's learn how to declare a variable and assign it's value later.

var a int
a = 5
Enter fullscreen mode Exit fullscreen mode

You must be wondering why have I written the keyword int after the variable name. Well in our previous example where we declared the name of our variable and assigned it a value immediately, our compiler was seeing the value and understanding what type can the variable hold. By what type a variable can hold, I mean one variable can hold data s of only one type that is either integers (numbers without decimal), floating-point numbers (numbers with decimals), string (anything within double quotes), etc. We shall learn more about these later. So as of now we need to know that when we are declaring a variable we must also mention it's type. We use int for integer, float for floating point, string for string type. Here's an example:

var a float
var b int
var c string
Enter fullscreen mode Exit fullscreen mode

However, what if we assign values of other type to these variable. When we are assigning values of int to float, the compiler will implicitly change the integer to float, but while doing the vice versa, we shall get the error, as integer variables are only capable of storing numbers without decimal.
You can however explicitly type case it and store it, but then it would store till the decimal and not after the decimal.

var a float
a = 1 // No error
var b int
b = 4.2 // Error 
var c float
c = int(2.3) //No error as explicit typecasting 
//c stores 2 as int not capable of storing  after decimal
Enter fullscreen mode Exit fullscreen mode

However if you have the values ready and want to assign to the variable right away without using var or declaring the type, well we have some syntactical sugar for that! Just write the variable name followed by := and the value.

d := 45
f := 4.6
g := "Hello World"
// We don't have to declare the type or use var keyword
Enter fullscreen mode Exit fullscreen mode

Previously we had seen how to add values to these variables now let's learn how to perform arithmetic operations with those:

a := 2
b := 3
var c int 
c = a+b // add
var d int
d = b-a // subtract
var e int
e = a*b //multiply
var f int
f = b/a //divide
var g int
 g = 4/6 +(a*b) * e /c //mixed operation
Enter fullscreen mode Exit fullscreen mode

Now to print variable we don't need quotes, we just write the variable name in the parenthesis.

fmt.Println(a) // a is a declared variable with some value in it
Enter fullscreen mode Exit fullscreen mode

Great ! We now know how to score values in variable, declare variable, initialize variable, add values of other types into it, and print it.

Try it Yourself:

Now that you know how to work with variables try these:

  • Declare two variables with values 3 and 5 respectively, and interchange their value using a third variable, and Print the result (Hint : If a was 3 and b was 5, the final result should be a = 5 and b = 3)

  • Declare two variables with value 4 and 6 and interchange their values without using a third variable, and Print the result.

  • Declare two variables of int type and assign float values to it by typecasting, and Print the result. (Hint : a = int (3.4))

Summary :

In this part we've learned about how to write a go program. We have written our first go program, by printing hello world. Then we've learned about variables and different functions. In the next part we shall go over : Constants, user input, conditional structs, loops, functions, structs.

Thanks for reading

Thank you for reading!
Follow us on Twitter for more tech blogs.

Until next time,
Arindol

Top comments (0)