Go Beginners’ Essentials by Palash Kanti Kundu
is licensed under a Creative
Commons Attribution-NonCommercial-NoDerivatives 4.0
International License.
Introduction
In this short guide, I will provide short handy notes for go language essentials. This is meant for Go Beginners but experienced programmers. So, any one coming from C, Java, C#, Python, Javascript background, can quickly catch up. I will also link the exercise files present in the same repository for easy reference.
This will be a collection of brief notes, just enough to get you started using Go. Taking your skills beyond the basics is completely your choice. Please do not treat this as complete language reference.
Pre-requisites
- A Computer :)
- Go compiler. Head to http://golang.org and download go for your OS. Steps are mentioned in the website.
- Any Text Editor of your choice.
- Prior experience with programming language like C, C++, Java, C#, Python. As the following notes will draw lots of analogy between the languages.
Introduction to Go
Go is a modern language which solves problems of some of the current programming languages. Companies like Google, Amazon are trying to leverage its out of box concurrency handling. Projects like Docker and Kubernetes are being written in Go.
In my opinion Go
is -
- C/C++ without the noisy pointer arithmatic
- Java/C# without
try
,catch
- Java/C# without overloading
- Java/C# without inheritance
- C/C++ with built-in concurrency handling
- C/C++ with garbage collection
- Java/C# without the need of a Virtual Machine
Some unique features of Go
are -
- Unused variable/package detection during compile time itself, resulting in optimal executable file genration and optimal memory usage
- Extreme level of type checking during compilation, eliminating the need of bugs caused by typecasting during runtime.
- You do not need
public
orprivate
keyword still make your variables or methods public or private - A built-in formatting tool to avoid the Formatting Problems in a multi developer system.
Basics
Exercise File: 1.go
- Similar Commenting Styles from C, C++, Java
- Semi-colon are not mandatory.
- Has concept of packages like java and you have to import necessary packages to run the program
- You must need a main package definition for running on console
- You must need a main function definition for running on console
go run
runs the filego build
creates an executable based on the platform you are running- Strings are automatically UTF. You do not need special packages to support multi-lingual system.
go fmt
command formats the source code as per its own standards thus solving the problem of a multi-developer development system where each developer follows their own formatting styles.- Go built application has an associated application run time. No Virtual Machine is required to run the application.
- Go has some of the Object Oriented Features - Interfaces, Custom Types, Structs, Methods
- Go does not have these Object Oriented Features - Inheritance, Polymorphism, Method or Operator overloading, implicit numeric conversion, Exception Handling
Variable Declaration
Exercise Files: 2.1.go, 2.2.go, 2.3.go, 2.4.go
- Variable declaration is a mix of javascript var and C/Java type declaration -
var x int
- Go has many integer definitions -
int8
,int16
,int32
,int64
,int
. Theint
type defaults to 32 bit or 64 bit based on platform. So, be careful if you have specific use case. Oherwise, you may go out of space or may get errors supporting your desired values. - Go also supports unsigned integer definitions like -
uint8
,uint16
,uint32
,uint64
anduint
. Automatic size definition goes foruint
as well. - Go has an alias for
uint8
and that isbyte
- Floats are either
float32
orfloat64
. No automatic definition for floats. - Default value for number type variables are 0 or 0
- If your program consists of any unused variable, the program will not even compile. So, get rid of memory issues in the compile time itself. Imagine, you have declared an array of
int64
of size 86400 * 64 and left it unused, essentially you are wasting almost 42 MB of main memory. Go, gets rid of that during compile time itself. - Go, even raises compiler error for unused but assigned variables
- Like unused variables, go raises compilation error for unused imports too
- However, go does not raise error for a blank function.
- You can get around the compilation error of unused variable by throwing away the value. You can name thhe variable as
_
to throw away its value
Strong type check system
Exercise Files: 3.1.go, 3.2.go, 3.3.go, 3.4.go, 3.5.go
- Go has a very strong type check system in place
- Go does not allow you to assign integer variables to float variables
- Operation between an integer and a float is not allowed
- Operation between an integer and an unsigned integer is not allowed
- Operation between float32 and float64 is also not allowed
- Division between two integers results an integer
- To get the float result, declare all associated variables as floats
- Like python you can leave the type inference on compiler. You can use
:=
operator for that - You can assign multiple variables on a single line using
,
Branching
Exercise Files: 4.1.go (Requires an integer console argument), 4.2.go
Usage: go run 4.1.go 7 go run 4.2.go 1
- Supports if else ladder, however like python you do not need parenthesis to be wrapped around the condition
- Conditional statements can have
&&
and||
- If conditions have an optional assignment statement
- Also supports switch and like Java, C# it supports string variables in the condition
- You do not need
break
statement inswitch
- Multiple cases can be comma separated
default
is optionalswitch
can work without a condition, which is an alternative to if/elseswitch
also can have optional assignment- The starting parenthesis must be placed on the same line as of the if/switch statement
Looping
Exercise File: 5.go, fizzbuzz.go
- go has only
for
loop for
can be used aswhile
andwhile true
loop as well- You can use
break
andcontinue
within loop
Basic Understanding of Strings
Exercise File: 6.go
- String is an immutable byte (uint8) array in go
- In the built in package, you get some string handling operations like, we get
strlen()
in C - Go string slices can be taken based on array indexes, syntax is like list slices in python
- Like Java, C# strings in go can be concatenated
- As already mentioned earlier, strings are by default unicode in go
- Multi line strings can be created using backticks
- In the
fmt
package, we also get a funtionSprintf
. This function returns astring
instead of displaying on console.
Basic Understanding of Slices
Exercise File: 7.go
- A
slice
is a wrapper over actual array in go - The declaration of
array
andslice
are similar except you remove the length in definition ofslice
whilearray
is fixed length - Like
ArrayList
in Java,slice
is graowable. For all practical purposes, I would like to thinkslice
asArrayList
in Java orList
in C# orList
in python. Though the concept is not exactly the same, they work similar. len
function can be used over slices, the indexing and taking out a slice from an array or another slice is pretty similar as of python or as discussed in the basic understanding of strings- All elements of the same slice must be of same type
- You can use
for
loop to iterate over a slice - You can use
range
keyword for iteration - You can use
range
with two variables that gives both values and indexes
Map
Exercise File: 8.go
map
in go is same asMap<T, T>
in java orDictionary<T, T>
in dotnet ordict
in python- You declare a
map
usingmap
keyword - While initializing map, you need the trailing comma and that’s a must
- You can get value of a key similar like python or C#
- One catch of go
map
, if you want to query for a key that does not exist in the map, it returns the default value for the type of the value. - To check if the key exists in a map, you need double context return
len
function returns the number of keys present in map- Upserting a value in
map
is similar of python - To delete a value from
map
use builtindelete
function - Iteration of map can be done using
for
loop withrange
either in single or in double context form
Functions
Exercise File: 9.go
- You define functions in go similar to C functions or Java functions, only the return type or variable types are declared post the variable or function definition.
e.g. func add(a int, b int) int
this code defines an add
function with two integer parameters and integer return type
- In go, you can return more than one variable, you use parenthesis to group the return type
e.g. func divide(dividend int, divisor int) (int, int, error)
declares divide function which can return three output. error
is a special type in go. I would like to think as Exception
in Java.
- You can return multiple values simply as comma separated
e.g. return dividend / divisor, dividend % divisor, nil
. nil
is Go is comparable with null
in Java/C#
-
Error returning is heavily utilised in go and we already used error earlier in this series to check the presence of error in the return. Well, this is something like, checking
HTTP Status Code
before dealing with the response. -
Calling a function is exactly the same as calling a function in C/Javascript
-
If a function returns more than one value, we have to use those many variables to assign the returns.
e.g. quotient, remainder, error := divide(5,0)
. You can also discard values that you won’t use by simply using _
to get rid of unused variable error (quotient, _, _ = divide(10,3)
will discard the remainder and the error)
Pointers
Exercise Files: 10.1.go, 10.2.go
- Like Java, primitive types are passed by value, even primitive arrays and strings. Remember
string
is an array ofuint
- All other values are passed by reference including slices
Destructors
Exercise File: 11.go
- The
__del__()
in python orfinalize()
in Java can be compared todefer
keywords in go - Go autoamatically cleans up the memory using garbage collector but for other resources like file, network, you can use the
defer
defer
statements are executed in reversedefer
statements will run regardless of if the code ran successfully or threw error
Structs
Exercise File: 12.go
- Like C, you can define your own
struct
, this works similar as a class in Java or C#. The definition can be done usingtype
andstruct
keywords. - You need to create the instance of the
struct
to be used in your code - You can create an instance of
struct
simply like C# but without thenew
keyword - If you leave any attribute empty while creating the struct, they will get default value according to the type
- The assigning of values in
struct
is similar like assigning values inmap
- While prining the value, it only prints the values stored in the attrbutes
- To see the
struct
likejson
you can use the+v
inprintf
struct
can have one or more method associated with it- Defining method on
struct
is similar to that of defining function except you have to mention on which struct the method works upon - Like functions, methods too can be either pass by value or pass by reference. Pass by reference is more common
- To define a method that is pass by value, we use the syntax -
func (p Product) Value() float64
wherep
is the name of the variableProduct
is the definedstruct
andValue
is the name of the method. Opening and closing braces define it has a method. This kind of methods do not change the value of thestruct
attributes. - To define a method that is pass by reference, we use the syntax -
func (p *Product) SellProduct()
. Notice the asterix before thestruct
type. This type of method can change the value of thestruct
attributes. The asteric defines that the method works on the pointer of thestruct
- Invoking method on
struct
is similar to that of invoking methods on Java or C#. - You can write a constructor function in go and it behaves like a constructor in Java or C#