Go Beginners’ Essentials by Palash Kanti Kundu is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.
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.
- 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
- 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
privatekeyword still make your variables or methods public or private
- A built-in formatting tool to avoid the Formatting Problems in a multi developer system.
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 runruns the file
go buildcreates 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 fmtcommand 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
Exercise Files: 2.1.go, 2.2.go, 2.3.go, 2.4.go
var x int
- Go has many integer definitions -
inttype 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 -
uint. Automatic size definition goes for
- Go has an alias for
uint8and that is
- Floats are either
float64. 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
int64of 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
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
- 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
- Multiple cases can be comma separated
switchcan work without a condition, which is an alternative to if/else
switchalso can have optional assignment
- The starting parenthesis must be placed on the same line as of the if/switch statement
Exercise File: 5.go, fizzbuzz.go
- go has only
forcan be used as
while trueloop as well
- You can use
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
- 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
fmtpackage, we also get a funtion
Sprintf. This function returns a
stringinstead of displaying on console.
Basic Understanding of Slices
Exercise File: 7.go
sliceis a wrapper over actual array in go
- The declaration of
sliceare similar except you remove the length in definition of
arrayis fixed length
sliceis graowable. For all practical purposes, I would like to think
ArrayListin Java or
Listin C# or
Listin python. Though the concept is not exactly the same, they work similar.
lenfunction 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
forloop to iterate over a slice
- You can use
rangekeyword for iteration
- You can use
rangewith two variables that gives both values and indexes
Exercise File: 8.go
mapin go is same as
Map<T, T>in java or
Dictionary<T, T>in dotnet or
- You declare a
- 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
lenfunction returns the number of keys present in map
- Upserting a value in
mapis similar of python
- To delete a value from
- Iteration of map can be done using
rangeeither in single or in double context form
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.
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
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
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 Codebefore dealing with the response.
If a function returns more than one value, we have to use those many variables to assign the returns.
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)
Exercise Files: 10.1.go, 10.2.go
- Like Java, primitive types are passed by value, even primitive arrays and strings. Remember
stringis an array of
- All other values are passed by reference including slices
Exercise File: 11.go
__del__()in python or
finalize()in Java can be compared to
deferkeywords in go
- Go autoamatically cleans up the memory using garbage collector but for other resources like file, network, you can use the
deferstatements are executed in reverse
deferstatements will run regardless of if the code ran successfully or threw error
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 using
- You need to create the instance of the
structto be used in your code
- You can create an instance of
structsimply like C# but without the
- If you leave any attribute empty while creating the struct, they will get default value according to the type
- The assigning of values in
structis similar like assigning values in
- While prining the value, it only prints the values stored in the attrbutes
- To see the
jsonyou can use the
structcan have one or more method associated with it
- Defining method on
structis 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() float64where
pis the name of the variable
Productis the defined
Valueis the name of the method. Opening and closing braces define it has a method. This kind of methods do not change the value of the
- To define a method that is pass by reference, we use the syntax -
func (p *Product) SellProduct(). Notice the asterix before the
structtype. This type of method can change the value of the
structattributes. The asteric defines that the method works on the pointer of the
- Invoking method on
structis 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#