Introduction to Go
Dive into the world of Go Language and start your journey.
What is Golang
Go is an open-source programming language that makes it easy to build simple, reliable, and efficient software.
It was designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson. This piece of information is important as this language is developed to handle the scale at which Google operates.
It is a statically typed, compiled programming language. So datatypes declaration matters and it does not infer types like Python or other dynamical typed languages. It is used as a system language mostly used for the backend, and server-side working.
Why do we use Golang
Compiler - Go lang is a compiled language, procedural language, so there are strict programming rules and established ways to perform a task. Go lang has a super-fast compiler. You can compile a large program in a few seconds. The compiler also has such advantages as error checking, code optimization, and facilitation of deployment. Cross-compiling is another excellent feature, which makes Golang apps compatible with many OS and platforms.
Simplicity and Readability - Readability, and maintainability are a priority in Go lang, unlike other languages which try to make themselves feature-rich. Go lang only has features that are relevant and do not make the language complex by adding a number of things this minimalistic approach, makes it very easy to get started with. You will be able to go through someone else's go code, no matter how large the codebase, and each and every line will be very much readable and understandable. It is very readable and it has a build-in formatter so everyone's code looks the same even if it was not originally written that way, go will format it for you.
Static typing - The go language is a statically compiled language, which provides static typing in the program. You have to be very explicit in what you are typing, there is not a lot of magic happening like in the case of Python. Go lang is a case-sensitive language so you need to be careful about that too.
Concurrency and Scalability- In the Go Language, "Go routine" is the basic fundamental unit to obtain the concurrency in your developing project. Goroutines are very light weighted and very easy to use in the program. It is as easy as defining a keyword before a function inside the program. It allows the user to handle millions of goroutines or go channels parallelly, at the same time. These goroutines and go channels are part of the concurrency. Goroutines have several other merits compared to threads. All in all, Go is a powerful tool in terms of concurrency, while the concurrency execution code is simple and beautiful.
Testing Capability — The Go language has a great testing capability. With just the “go test” command you will be able to test your code written in “*_test.go” files. For making any program reliable, testing is an integral part, you should add a test function along with the actual function each time you write some code.
Standard library - Go language has a strong standard library system. It has a powerful and large set of library packages, which allows you to create your code easily in the program. The go language library has all the essential tools with which you can easily create a program inside it. You can access the standard library here.
System Programming and Cloud Computing capabilities - Go was made with scalability and reliability kept in mind makes it a go-to choice for system-level programming as it exhibits many similarities with system programming languages like C and Cloud computing where scalability is paramount. A lot of DevOps tools are built-in Go - you can extend the tools or use the tools easily.
Getting started
Go playground
You can start with Go playground to use go from your browser initially just to see how it works. If you are completely new to programming and are afraid you might break things, this is a completely safe place to mess around.
Installation
Go through the official website and choose the installer for your own OS. Through here.
Focus on the concepts!!!
Concepts are important and whatever you learn is applicable to other programming languages. Basic concepts such as getting input, displaying output, using comments, using variables and constants, data types, type-conversion, math operators, logical operators, and using if-else statements, loops, and functions will help you get started with any language.
Once you have an understanding of the basic concepts it is easier to build on top of that and learn advanced concepts such as concurrency.
Get User Input
There are multiple ways to receive input from the user, we will go through the most common ones.
- Scan()
//Every Go program needs a main function otherwise it won't run. Compile language needs a starting point.
package main
//The "fmt" package includes the necessary tools to get input and display output to the console.
import (
"fmt"
)
func main() {
var name string
fmt.Print("Enter your name: ")
fmt.Scan(&name) //Use & symbol then name of the variable to get input.
fmt.Println("Hello,", name, "you are learning Go.")
}
- Scanln() - The Scanln() function is similar to Scan(), but it stops scanning for inputs at a newline (at the press of the Enter key.).
package main
import (
"fmt"
)
func main() {
var name string
var age int
fmt.Print("Enter your name and age: ")
fmt.Scanln(&name, &age)
fmt.Println("Hello,", name, "you are", age, "years old.")
}
- Scanf() - The Scanf() function receives the inputs and stores them based on the determined formats for its arguments.
package main
import (
"fmt"
)
func main() {
var name string
var age int
// Scanln and Scanf examples are similar,
// In this example the inputs are received exactly the same way
// as defined in Scanf formatting. First name then age
// Try age then name in Scanln and Scanf to see the difference
fmt.Print("Enter your name and age: ")
fmt.Scanf("%s %v", &name, &age)
fmt.Println("Hello,", name, "you are", age, "years old.")
}
Display output
There are multiple ways to display output on the console, we will go through the most common ones.
- Print()
- Println()
- Printf()
package main
//Importing the fmt package for printing
import "fmt"
func main() {
var name string
var language string
name = "I"
language = "Go!"
fmt.Println("Hello playground.") //Displaying the output of the String
fmt.Print(4 + 2)
fmt.Println("")
fmt.Printf("%s am learning %s .\n", name, language)
}
//Println - Prints the output and moves the prompt to a new line.
//Print - Prints the line and does not move prompt to a new line.
//Printf - Operates like fmt.Print but allows for output formatting.
Comments
Comments are just bits of text the interpreter or compiler will ignore. You can use it for notes, temporarily remove code for some time, or just to document something you want to remember.
//This is an example of a comment in Go
package main
func main() {
}
Variables
A Variable is a placeholder that can change. You can set a variable with a value and use this variable where ever you want to use it within the scope of the declaration. Variables can be reassigned with the value of the same data type.
package main
import "fmt"
func main() {
//Using Variable
var name string //Variable Declaration
var language string
name = "I" //Variable Assignment
language = "Go!"
name = "Gopher"
//var name int //Variable re-declaration will give an error but variable assignment with the same data type is allowed.
//var example string = "This is Declaration and Assignment together."
fmt.Printf("%s am learning %s .\n", name, language)
}
Type inferencing, dynamic languages will try to figure out what type something is, So will Go even if it is statically typed language.
package main
import "fmt"
func main() {
//Using Variable
var language string //Variable Declaration
language = "Go!" //Variable Assignment
name := "I" //Shorthand for Variable Assignment and Declaration
fmt.Printf("%s am learning %s .\n", name, language)
}
Constants
When you want to use some variable whose value does not change in the scope of the code. You use constants. This allows us to set a constant whose value you can use anywhere and cannot be reassigned once declared.
package main
import "fmt"
//Constant declaration
const sun string = "Sun rises in the East."
func main() {
//var name string
//var language string
name := "I"
language := "Go!"
fmt.Println(sun) //Using constant
fmt.Printf("%s am learning %s .\n", name, language)
}
Datatypes
In the Go language, the type is divided into four categories which are:
- Basic type: Numbers, Strings, and booleans
- Aggregate type: Array and structs
- Reference type: Pointers, slices, maps, functions, and channels
- Interface type
Try out one example of each for your practice. Once you are comfortable with the basics use this resource for practicing.
Math Operators
Basic math operators in Go lang are,
- Addition
- Subtraction
- Multiplication
- Division
- Modulus
- Increment
- Decrement
package main
import "fmt"
func main() {
var a int = 2
var b int = 4
fmt.Println(a + b) //Addition
fmt.Println(b - a) //Substraction
fmt.Println(a * b) //Multiplication
fmt.Println(b / a) //Division
fmt.Println(b % a) //Modulus - This returns the remainder
a++
fmt.Println(a) //Increment
a--
fmt.Println(a) //Decrement
}
With the basics out of the way let's dive deeper into what makes programming so powerful, Logic!
Logical Operators
Comparison Operators or Logical Operators are operators who compare two values to each other.
- "==" Equality
- "!=" Inequality
- ">" Greater than
- "<" Less than
- ">=" Greater than/Equal
- "<=" Less than/Equal
- "||" Or
- "&&" And
package main
import "fmt"
func main() {
var a int = 2
var b int = 4
fmt.Println(a == b) //Equality - Checks equality, returns False
fmt.Println(b != a) //Inequality -Checks inequality, returns True
fmt.Println(a > b) //Greater than -Checks if a is greter than b, returns false
fmt.Println(a < b) //Less than -Checks if a is less than b, returns true
fmt.Println(a >= b) //Greater than/equal -Checks if a is greater than or equal to b, returns false
fmt.Println(a <= b) //Less than/equal -Checks if a is less than or equal to b, returns true
fmt.Println(a < b || a > b) //Or -Checks either first statement or second statement is true, returns true
fmt.Println(a < b && a > b) //And -Check if both first and the second statement are true, returns false
}
You can even compare Strings using comparator operators, try that on your own and see what results you get.
If-else statements
If a condition is true, execute a statement else execute another statement. This is the whole idea behind the if-else condition.
This concept is common across all programming languages
//Use the If statement to check if a person is allowed to drink
// Let's say the legal drinking age is 21
package main
import "fmt"
func main(){
age := 21
if( age >=21){
fmt.Print("You may enter the Bar, you are old enough to drink.")
}else{
fmt.Print("You cannot enter the Bar, you are not Old enough to drink.")
}
}
Loops
Here things might get a bit confusing, so feel free to go through it multiple times (pun intended😜)
Loops are used to run a set of instructions multiple times. There are different types of loops
- For loop
- While loop
- Do while loop
But, Go has only For loops. For loops run for as long as a scenario you specify is true.
//Our starting number is 0. Till user-defined integer is reached. Print all of the numbers
package main
import "fmt"
func main() {
var num int
fmt.Println("Enter the number:")
fmt.Scan(&num)
for x := 0; x <= num; x++ {
fmt.Println(x)
}
}
Functions - Reusable Code
Functions are a beautiful concept in programming. Imagine having to use the addition of different numbers, won't it be nice if you declare the logic once and just use it in your code. Functions do exactly that!
You give a function a name and you can use the function anywhere in the code. It takes in data, processes it, or does some logical operation on it then returns an output. It is not necessary to always do some operations on the input, there can be output without any operation too.
package main
import "fmt"
func add(a int, b int) int {
return (a + b)
}
//Function needs to be defined with the parameter's datatype as will as return datatype
func minus(a int, b int) int {
return (a - b)
}
func main() {
fmt.Println(add(2, 3))
fmt.Println(add(929842, 7823)) // You can all the function again and again
fmt.Println(minus(5, 1))
}
Conclusion
Go is a very efficient and powerful language if you want to use it for server-side applications, scalability solutions, and system programming.
It is a very popular language too as the Go team surveyed 11,840 developers(aka gophers) for its 2021 Go Developer Survey and found 54% were "very satisfied" with the state of the language while 38% said they were "somewhat satisfied". However, as Google user experience research Alice Merrick notes, the fact that 92% of respondents overall were at least "somewhat satisfied" with Go is consistent with past surveys.
Now, you have basic knowledge about Go. I suggest you get programming and try to solve some made-up questions using Go lang this approach will help you learn by doing.
Resources
- Go lang Documentation. Reading technical documentation is a skill. To find out information go through the documentation. It doesn't provide the context around the stuff you want to learn but it is the go-to place for information. See for yourself what have you learned in this blog.
- A tour of Go
- Go by Example
- Go Standard Library
- Getting input GeeksforGeeks
- Go datatypes GeeksforGeeks
- Intro to DevOps- Intro to Programming with Go Pt 1, video by mastermnd which Inspired me to write this blog.
- Intro to DevOps- Intro to Programming with Go Pt 2, video by mastermnd