# Code With Go

Build everything with Go!

### Core Mission&#x20;

Our core mission is to empower everyone to "learn to program" using Go programming language. Our mission is to make high quality learning resources freely available for everyone. We also provide free of cost in-person training workshops for underrepresented groups as well as for student. Reach out to [us](https://docs.google.com/forms/d/e/1FAIpQLSeQIYQWuiWtbfhBlFcQSXXQaeYh5CfHRAKNK-p0-ilpuYtljw/viewform) if you want us to teach or speak at event.

### Why Go?&#x20;

* Go is simple - Go is simple to get started. It's not scary especially for new comers.&#x20;
* Go is powerful - Go is very powerful. Modern core platforms like Docker, Kubernetes, Hyper-ledger Fabric Blockchain etc. are being on Go.&#x20;
* Go has easy concurrency - Concurrent programming is necessary evil for everyone. Go has simple concurrency model.
* Go is widely used in web applications and micro-services.
* Go Community - it is estimated that there are around 0.8 million to 1.6 million users worldwide \~ [source](https://research.swtch.com/gophercount)

### About Me

I am software developer based in Pune, India. You can reach me on Twitter [@gophersumit](https://twitter.com/gophersumit)


# 01. What, Who, Why and Where?

Where Go is used

### What is build using Go?

* Docker - Container
* Kubernetes - Container Management System
* DGraph - Graph Database
* Hyperledger Fabric - Blockchain platform

and many more! These are all new platforms which are build in last decade.

### Who is using Go?

* Uber
* Google
* Twitch
* SendGrid
* Medium

most of small scale and medium scale companies are adopting Go. Traditional companies will most probably see huge growth in coming years.

### Why Go ?

* easy to learn
* standardized formatting
* multi-platform
* garbage collected
* focus on large scale maintainable code
* **easy concurrency**

### Where Can I run Go?

* Linux, Windows and MacOS
* Container
* Serverless Platforms
* Browsers
* Robots
* IoT Devices
* Drones!

### Blog Resources

{% embed url="<https://letzgro.net/blog/9-reasons-to-choose-golang-for-your-next-web-application/>" %}

{% embed url="<https://medium.com/@kevalpatel2106/why-should-you-learn-go-f607681fad65>" %}

{% embed url="<https://medium.com/@Sandra_Parker/why-golang-is-the-future-part-1-ed7dd4f419d>" %}

{% embed url="<https://medium.com/@Sandra_Parker/why-golang-is-the-future-part-2-1f984ae8f1a4>" %}

{% embed url="<https://hub.packtpub.com/why-golan-is-the-fastest-growing-language-on-github/>" %}

{% embed url="<https://opensource.com/article/17/11/why-go-grows>" %}

{% embed url="<https://hackernoon.com/5-reasons-why-we-switched-from-python-to-go-4414d5f42690>" %}

### Gophercon

{% embed url="<https://www.youtube.com/watch?v=cQ7STILAS0M&t=10s>" %}
&#x20;Rob explains how Go's simplicity hides a great deal of complexity, and that both the simplicity and complexity are part of the design.
{% endembed %}


# 02. Compiled vs Interpreted languages

### A Comparison

| Compiled Language                                                  | Interpreted Language                                                           |
| ------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
| The original program is translated into native machine instruction | The original program is translated into something else                         |
| Code is executed directly by Hardware                              | Code is executed by special program called Interpreter                         |
| Generally Faster and more efficient at run-time.                   | Comparatively slows at run-time.                                               |
| Additional compilation steps are required.                         | No compilation step is required. Program is ready to execute as soon as typed. |
| More control over hardware like and CPU and Memory.                | Hardware is generally not accessible.                                          |
| Examples : C, C++, Erlang, Haskell, Rust, and Go.                  | Examples : PHP, Ruby, Python, and JavaScript                                   |

### Blog Resources

{% embed url="<https://guide.freecodecamp.org/computer-science/compiled-versus-interpreted-languages/>" %}

{% embed url="<https://medium.com/@DHGorman/a-crash-course-in-interpreted-vs-compiled-languages-5531978930b6>" %}

### Video Resource

{% embed url="<https://www.youtube.com/watch?v=JNMy969SjyU>" %}
Compilation cs Interpretation
{% endembed %}


# 03. Types of Type!

Because type is life!

## Type System

{% hint style="success" %}
Type system is a set of rules that assigns a property called type to the various constructs of a computer program, such as variables, expressions, functions or modules
{% endhint %}

### Type Error

{% hint style="success" %}
&#x20;A *type error* is erroneous or undesirable *program* behavior caused by a discrepancy between differing data types for the *program's* constants, variables, and methods.
{% endhint %}

### Type Safety

{% hint style="success" %}
The extent to which a programming language discourages or prevents type errors
{% endhint %}

### Strong Typing

{% hint style="success" %}
A strongly typed language typically disallows implicit conversions between unrelated types
{% endhint %}

### Weak Typing

{% hint style="success" %}
A weakly typed language makes conversions between unrelated types implicitly
{% endhint %}

### Static Type Checking

{% hint style="success" %}
Static type checking is the process of verifying the type safety of a program based on analysis of source code.
{% endhint %}

### Dynamic Type Checking

{% hint style="success" %}
Dynamic type checking is the process of verifying the type safety of a program at run-time
{% endhint %}

### Manifest Typing

{% hint style="success" %}
Manifest typing is explicit identification by developer of the type of each variable being declared
{% endhint %}

### Type Inference

{% hint style="success" %}
Automatic detection of type based on usage.
{% endhint %}

### Duck Typing

{% hint style="success" %}
If it walks like a duck and it quacks like a duck, then it must be a duck
{% endhint %}

## Blog Posts

{% embed url="<https://www.ardanlabs.com/blog/2013/07/understanding-type-in-go.html>" %}


# 04. Stack and Heap Memory

A simple comparison

### Comparison of Stack and Heap memory

| Stack Memory                                                               | Heap Memory                                                                        |
| -------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| Generally, memory is automatically managed by program.                     | Generally, memory management to be done by programmer.                             |
| Traditionally used to stores temporary variables created by each function. | Variables created on the heap are accessible by any function, anywhere in program. |
| Limit on stack memory size.                                                | No specific limit on heap memory size.                                             |
| Self cleaning memory.                                                      | Memory cleanup required explicitly.                                                |

### Gophercon - Understanding Allocations: the Stack and the Heap - GopherCon SG 2019

{% embed url="<https://www.youtube.com/watch?v=ZMZpH4yT7M0>" %}
Like C, Go uses both stack and heap memory. How can a Gopher know which is being used?&#x20;
{% endembed %}

### Blog Posts

{% embed url="<https://www.ardanlabs.com/blog/2013/07/understanding-pointers-and-memory.html>" %}


# 05. Garbage Collection

Cleaning up!

### What is Garbage Collection?

Whenever we are working with heap memory, we as programmer are responsible for managing memory. Managing heap memory has traditionally been difficult task. This is the case with traditional programming languages like C,C++. &#x20;

> Microsoft: 70 percent of all security bugs are memory safety issues - ZDNet

source : <https://www.zdnet.com/article/microsoft-70-percent-of-all-security-bugs-are-memory-safety-issues/>

Since memory management has been tedious tasks, various programming languages have evolved to provide these features. C#, Java, Python all provides memory management as a feature so that programmer has no longer to worry about memory management.

The feature of language to manage memory for programmer is called Garbage collection. Garbage collection can be thought as a side running program that manages heap allocation and de-allocation.

### Blog Posts

{% embed url="<https://www.ardanlabs.com/blog/2018/12/garbage-collection-in-go-part1-semantics.html>" %}

{% embed url="<https://www.ardanlabs.com/blog/2019/05/garbage-collection-in-go-part2-gctraces.html>" %}

{% embed url="<https://www.ardanlabs.com/blog/2019/07/garbage-collection-in-go-part3-gcpacing.html>" %}

{% embed url="<https://blog.golang.org/ismmkeynote>" %}

### Video Resources

{% embed url="<https://www.youtube.com/watch?v=q4HoWwdZUHs>" %}
How to be sympathetic with the Go garbage collector, regardless of the current implementation or how it changes in the future
{% endembed %}

{% embed url="<https://www.youtube.com/watch?v=bMujSVMarqY>" %}
Golang UK Conference 2017 | Will Sewell & Jim Fisher - Golang's Realtime GC in Theory and Practice
{% endembed %}


# 06. About Go

A Brief introduction to Go

> Go is an open source programming language that makes it easy to build **simple**, **reliable**, and **efficient** software. - Golang.org

Go is best described as "C" for 21st century. Go was developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google and open sourced in 2009. Go is general purpose programming language that can be at various places.

> Go has no implicit numeric conversions, no constructors or destructors, no operator overloading, no default parameter values, no inheritance, no generics, no exceptions, no macros, no function annotations, and no thread-local storage. - **The Go Programming Language by Brian W. Kernighan, Alan A. A. Donovan** &#x20;

### So what is Go?

* Go is general purpose programming language.&#x20;
* Go is compiled language.&#x20;
* Go is more type safe than C,C++.
* Go is strongly typed language.
* Go has static type checking.
* Go needs manifest typing. Compiler has to know each type at compile time.
* Go compiler can also perform type inference in many cases.
* Go has duck typing like features like interfaces.
* Overall Go is extremely simple, expressive and powerful.

### Why Go was created?

Go is created to bridge gap between safety and performance. Languages like C, C++ are very performant, but at the same time, they are not safe. On other hand languages like Ruby, Python are safer, but are slower. Go sits at a sweet spot where, Go is fast enough to build platforms, at the same time provides safety like Ruby, Python.

### What Problems Go tries to solve?

* slow builds
* uncontrolled dependencies
* each programmer using a different subset of the language
* poor program understanding (code hard to read, poorly documented, and so on)
* duplication of effort
* cost of updates
* version skew
* difficulty of writing automatic tools
* cross-language builds&#x20;

{% embed url="<https://talks.golang.org/2012/splash.article>" %}

Who is using Go ?

{% embed url="<https://thenewstack.io/who-is-the-go-developer>" %}

> In a nutshell, we wanted a language with the safety and performance of statically compiled languages such as C++ and Java, but the lightness and fun of dynamically typed interpreted languages such as Python - Rob Pike

{% embed url="<https://www.red-gate.com/simple-talk/opinion/geek-of-the-week/rob-pike-geek-of-the-week>" %}

{% embed url="<https://play.golang.org/p/HmnNoBf0p1z>" %}


# 07. Go Playground

Run without installing!

{% hint style="info" %}
&#x20;The Go Playground is a web service that runs on [golang.org](https://golang.org/)'s servers.
{% endhint %}

We can use Go playground to edit and run simple Go programs. Head to playground at : <https://play.golang.org/>&#x20;

Delete existing code and type in below code manually. (Remember programming is all about muscle memory!)

{% code title="hello.go" %}

```go
package main

import "fmt"

func main() {
	fmt.Println("Hello, Pune!")
}

```

{% endcode %}

Let's understand how this code works:

{% hint style="success" %}
Every Go program starts execution from *main()*
{% endhint %}

```go
func main(){}
```

Main is the signal to compiler to start execution of code from *here.* This is entry point of our application.

{% hint style="success" %}
Every Go program should be part of a package
{% endhint %}

```go
package main
```

This declares that our program is part of package "main". Packages are used to bundle similar code that can be reused easily.

{% hint style="success" %}
Go program can use external packages using import
{% endhint %}

```go
import "fmt"
```

We are importing **fmt** package using import statement. Compiler will find this package and import in our program before we can use it.

We are using **Println** method from **fmt** package to print output to console. How to print output to console is implemented by fmt package, we do not have to write (re-write!) code to do it!


# 08. Hello, World!

### Go Program Order

* package statement
* imports statement
* functions, variables, constants etc.

{% code title="main.go" %}

```go
package main

import "fmt"

func main() {
	fmt.Println("Hello, Pune!")
}
```

{% endcode %}

### Package statement

* each go file must start with package declaration.
* `package` is the keyword used to declare a package.

{% code title="main.go" %}

```go
package main
```

{% endcode %}

* packages are used modularity, encapsulation, separate compilation, and reuse.
* Go comes with lot of in-build library packages

{% embed url="<https://golang.org/pkg/>" %}

* `crypto` - cryptography related code.
* `fmt` - formatted input/output related code.
* `os` - operation system related code.
* `net/http` - http related code.

### Import statement

* import statements are used to import external packages.
* `import` is the keyword used to import a package.

{% code title="main.go" %}

```go
import "fmt"
```

{% endcode %}

* before using functionality provided by any package, it needs to be imported.
* multiple packages can be imported using single import clause.

{% code title="main.go" %}

```go
import (
	"fmt"
	"net/http"
	"os"
)
```

{% endcode %}

* unused imports are not allowed.

### Main package

* declaring a main package is way to telling Go that this is executable and not library.
* Main package should have method named `main` for Go to be able to execute it.
* effectively, main is starting point for application to run from a functionality point of view.

{% code title="main.go" %}

```go
func main() {
	fmt.Println("Hello, Pune!")
}
```

{% endcode %}

### Declaring a function

* function is a code block that can be called by name.
* a function is declared using `func` keyword followed by name of function.
* function name should be followed by round brackets `()`
* every function should have function body. This is defined using opening and closing curly braces `{}`
* ideally, function can accept input in the form of function parameters and return output in form of return values.

{% code title="main.go" %}

```go
func sayHello() {
	fmt.Println("Hello, Pune!")
}
```

{% endcode %}

### Calling a function

* function that are in same package can be called directly by name.
* function is called using function name followed by `()`
* functions in other packages needs to be called using package name followed by dot `.` and followed by function name.

{% code title="main.go" %}

```go
func sayHello() {
	fmt.Println("Hello, Pune!")
}
func main() {
	sayHello()
}
```

{% endcode %}

{% hint style="info" %}
Identify all the function call in code snippet below.
{% endhint %}

{% code title="main.go" %}

```go
package main

import "fmt"

func sayHello() {
	fmt.Println("Hello, Pune!")
}
func main() {
	sayHello()
	fmt.Println("Getting started is so easy")
	fmt.Println("And fun!")
}

```

{% endcode %}

{% embed url="<https://play.golang.org/p/VToCbUOQYat>" %}

{% hint style="warning" %}
Guess the output
{% endhint %}

{% code title="main.go" %}

```go
package main

import "fmt"

func main() 
{
	fmt.Println("Hello, Pune!")
}
```

{% endcode %}

{% hint style="success" %}
Opening Brace must be on same line where function starts.
{% endhint %}


# 09. Installing Go

## For Windows and Mac

1. Download Go from [https://golang.org/dl](https://golang.org/dl/)
2. Download Visual Studio Code from <https://code.visualstudio.com/download>
3. Install Go extension from <https://code.visualstudio.com/docs/languages/go>

## For Ubuntu

1. Install Go using Bash shell

```bash
sudo add-apt-repository ppa:longsleep/golang-backports
sudo apt-get update
sudo apt-get install golang-go
```

2\. Install VS Code from software center

3\. Install Go extension from <https://code.visualstudio.com/docs/languages/go>

## Checking installation

Open new terminal window and type in below command to verify Go is installed successfully.

```bash
go version
```

This should output current installed go version.


# 10. Variables

Naming memory locations

### What are Variables?

Variables are named memory locations, that are used to refer to data in our program. General format for variable is Go is: `var name type = expression`

Variable names must start with letter and can contain letter and number.

### Declaring variables

Variables are declared using `var`keyword. Before using variables, they need to be declared. For declaring variables:

* Use the var keyword.&#x20;
* Write a variable name.&#x20;
* Write the variable type.&#x20;
* Optionally, assign value using equals `=`

{% code title="main.go" %}

```go
func main() {
	var s string
	s = "sumit"
	var i, j, k int
}
```

{% endcode %}

Multiple variables of same type can be declared using comma separation in name. All declared variables should be used.Variable name can not be reserved keywords.

{% code title="keywords" %}

```go
break        default      func         
interface    select       case         
defer        go           map          
struct       chan         else         
goto         package      switch
const        fallthrough  if           
range        type         continue     
for          import       return       
var
```

{% endcode %}

### Short variable declaration

Short variable declaration may be used to declare and initialize local variables.It takes the form `name` `:=` `expression.`Below declarations are one and the same

{% code title="main.go" %}

```go
func main() {
	var s string
	s = "hello, world!"
	t := "hello, world!"

	var i int
	i = 42
	j := 42
}
```

{% endcode %}

### Variable Scope

Variables are visible only with the scope they are declared. We can access the variable so long as it’s in scope, but once a variable is no longer in scope, attempts to access it will report an error. Scope is defined by braces `{}`

### From the Docs

{% embed url="<https://golang.org/doc/effective_go.html#variables>" %}
Effective Go
{% endembed %}


# 11. Constants

Can not change me

### What are constants?

A `const` declaration defines named values that look syntactically like variables but whose value is constant.Instead of the `var` keyword, we use the `const` keyword.A value must be assigned while declaring constants.Constants only exists during compile time!

### Declaring constants

Constants are declared using `const` keyword.

{% code title="main.go" %}

```go
const pi = 3.14
```

{% endcode %}

### Constant Block

Similar to variable block, we can also have constant block.

{% code title="main.go" %}

```go
const (
	pi         = 3.14
	daysInWeek = 7
)
```

{% endcode %}

### IOTA

`iota` can be used to create enumerated constants. It is also called as constant generator.

{% code title="main.go" %}

```go
const (
	Sunday int = iota
)

func main() {
	fmt.Println(Sunday)
}
```

{% endcode %}

Benefits of using iota is that it will increment itself for next const declaration in same const block.

{% code title="main.go" %}

```go
const (
	Monday int = iota + 1
	Tuesday
	Wednesday
	Thursday
	Friday
	Saturday
	Sunday
)

func main() {
	fmt.Println(Monday, Tuesday, Wednesday, Thursday, 
	Friday, Saturday, Sunday)
}
// output : 1 2 3 4 5 6 7
```

{% endcode %}

### From the Docs

{% embed url="<https://golang.org/doc/effective_go.html#constants>" %}
Constants
{% endembed %}

### Blog Posts

{% embed url="<https://blog.golang.org/constants>" %}

{% embed url="<https://github.com/golang/go/wiki/Iota>" %}

{% embed url="<https://dlintw.github.io/gobyexample/public/constants-and-iota.html>" %}

{% embed url="<https://splice.com/blog/iota-elegant-constants-golang/>" %}


# 12. Integers

Using Natural Numbers

### Integer Types

* Integers are used to store natural numbers are 1,2,3.
* Go has 8 types on integers
* &#x20;`int8`, `int16`, `int32`, and `int64`, and corresponding unsigned versions `uint8`, `uint16`, `uint32`, and `uint64.`
* unsigned integers can store positive numbers only.
* 8,16,32 and 64 represents how many bits are used to store value.

| Bits | Signed                                                  | Unsigned                        |
| ---- | ------------------------------------------------------- | ------------------------------- |
| 8    | –128 to 127                                             | 0 to 255                        |
| 16   | –32,768 to 32,767                                       | 0 to 65535                      |
| 32   | –2,147,483,648 to 2,147,483,647                         | 0 to 4,294,967,295              |
| 64   | –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | 0 to 18,446,744,073,709,551,615 |

### Declaring Integers

Integers are declared using one of the 3 ways:

{% code title="main.go" %}

```go
var j int32 = 20
var i int = 10
var i = 10
i := 10
var k int
```

{% endcode %}

If we are not specifying type like in 2nd and 3rd declaration, it will default to `int`

Zero value for integer is `0`

{% hint style="success" %}
Always use short declaration way when assigning initial value. If you wish to initialize a variable to its zero value, use var declaration.
{% endhint %}

### Using Test Driven Development for integers

Learn how to do test driven development when using integers from Chris

{% embed url="<https://github.com/quii/learn-go-with-tests/blob/master/integers.md>" %}


# 12. Floats

### Float Type

* float types are used to represent numbers with decimal value.
* &#x20;Go provides two sizes of floating-point numbers, `float32` and `float64`.

{% code title="main.go" %}

```go
var myFloat float64
myFloat = 3.14
```

{% endcode %}

### Declaring Floats

Floats are declared using one of the following ways:

{% code title="main.go" %}

```go
var f float32 = 20.6
var h float64 = 40.2
var h = 40.2
h := 40.2
```

{% endcode %}

If we are not specifying type like in 3rd and 4th declaration, it will default to `float64`

Zero value for float is `0.0`


# 13. Boolean

### Boolean(bool) Type

Boolean has only two possible values, `true` and `false`

Conditions and comparison operators needs value to be bool Type.

{% code title="main.go" %}

```go
package main

import "fmt"

func main() {
	var shouldGo bool = true

	if shouldGo {
		fmt.Println("I should Go!")
	}

}
```

{% endcode %}

### Declaring Boolean

Boolean are declared using one of the following ways:

{% code title="main.go" %}

```go
var shouldBe bool = true
var shouldBe = true
shouldBe :=true
```

{% endcode %}

Zero value for bool is `false`


# 14. Strings

### String Types

String Types are used to store text like data.A string is an immutable sequence of bytes.

Go uses UTF-8 encoding to store strings.

> A character in UTF8 can be from 1 to 4 bytes long. UTF-8 can represent any character in the Unicode standard. UTF-8 is backwards compatible with ASCII. UTF-8 is the preferred encoding for e-mail and web pages - W3Schools.com

### Declaring String

Strings are declared using one of the following ways:

{% code title="main.go" %}

```go
	var str1 string = "Hello, World!"
	var str2 = "Hello, World!"
	str3 := "Hello, World!"
```

{% endcode %}

Zero value for string is empty string `""`

### Length of string

Build in `len` function can  be used to get number of bytes in string

{% code title="main.go" %}

```go
fmt.Printf("length of str1 is %d \n", len(str1))
```

{% endcode %}

### Sub-string operation

We can easily create substring from existing string using `s[i,j].`This operation always generates new string since string are immutable. `i` indicates starting index for substring including `i` and `j` indicates end index excluding `j`

{% code title="main.go" %}

```go
str4 := str1[7:13]
fmt.Println(str4)
```

{% endcode %}

### Blog Posts

{% embed url="<https://blog.golang.org/strings>" %}


# 15. Complex Numbers

### Complex Type

`complex` types are used to work with complex numbers. Go has  Go two types of complex numbers, `complex64` and `complex128`

To create complex number, we use build in `complex` function.

### Declaring Complex Number

Complex numbers can be declared using any of the below way

{% code title="main.go" %}

```
var c1 complex128 = complex(2, 3)
var c2 complex64 = complex(3, 4)
var c1 = complex(2, 3)
c1 := complex(2, 3)
```

{% endcode %}

When type is not specified, complex number defaults to `complex128`

Since complex numbers must be created using `complex()` function, these do not have a corresponding zero value.

&#x20;Go provides two sizes of complex numbers, `complex64` and `complex128` . These are used to represent complex numbers.

### Declaring Complex Type

We need to use in-build `complex` function to create complex type.

{% code title="main.go" %}

```go
var x  = complex(2, 2)
var x complex128 = complex(2,2)
var y complex64 = complex(3,4)
```

{% endcode %}

If no type is specified, it defaults to `complex128`


# 16. If Else

Control the flow

### If Statement

If like in most other programming languages, is used to control flow of execution based on condition. Common semantic for if statement is&#x20;

`if condition { code to execute}`

{% code title="main.go" %}

```go
flag := true

if flag {
	fmt.Println("Flag is present")
}
```

{% endcode %}

### Stronger Semantics

If statement in Go has stronger semantics than some other programming languages. We can not provide integer or string as condition for if statement.Condition has to be a Boolean value in if statement. Following code will not compile.

{% code title="main.go" %}

```go
count := 1
if "hello" {
	fmt.Println("Invalid if")
}
if count {
	fmt.Println("Invalid if")
}
```

{% endcode %}

Also, when code to execute is single statement, some programming languages allow to skip curly braces, but not in Go. As with other code blocks, curly braces need to start from same line.

### Multiple Branches

To work with multiple branches, Go provide `if...else` form

{% code title="main.go" %}

```go
marks := 70
if marks > 80 {
	fmt.Println("Great!")
} else if marks > 60 {
	fmt.Println("Good!")
} else if marks > 40 {
	fmt.Println("You can do better!")
}
```

{% endcode %}

Remember that once a if condition is satisfied, it will not check for remaining conditions in other else blocks.

### Ternary Operator

Go does not have ternary operator. This has been well addressed in Go FAQ.

> &#x20;The reason `?:` is absent from Go is that the language's designers had seen the operation used too often to create impenetrably complex expressions. The `if-else` form, although longer, is unquestionably clearer. A language needs only one conditional control flow construct. - <https://golang.org/doc/faq#Does_Go_have_a_ternary_form>

### GitHub Code

{% embed url="<https://github.com/gophersumit/codewithgo-samples/tree/master/if>" %}


# 17. Switch

### Switch Statement

When there are multiple branches, `if...else` code can get more verbose. Switch statement provide more efficient way to express multiple branches. Semantic for switch statement is&#x20;

```
switch condition {
    case x: 
        code to execute
    case y:
        code to execute   
    default:
        code to execute     
}
```

When one of the case statement is matched, that code is executed. Default block is executed when there is no matching case.

### No Fall-through

One of the difference switch statement has with other programming languages, is that if one of the case is matched, only that code is executed and switch statement break automatically. This means that cases do not fall-though automatically for switch statement in Go.

{% code title="main.go" %}

```go
i := 2
switch i {
case 1:
	fmt.Println("i is one")
case 2:
	fmt.Println("i is two")
case 3:
	fmt.Println("i is three")
case 4:
	fmt.Println("i is four")
}
```

{% endcode %}

Only `case 2` will be executed.

### Switch without expression

We can also define without any expression and case statement can take care of evaluating condition.

{% code title="main.go" %}

```go
dayOfWeek := 6
switch {
case dayOfWeek == 6 || dayOfWeek == 7:
	fmt.Println("It's weekend!")
case dayOfWeek < 6 && dayOfWeek > 0:
	fmt.Println("It's weekday!")
default:
	fmt.Println("You are not on Earth!")
}
```

{% endcode %}


# 18. For

Running Loops

### For Statement

When we need to repeat things, that's where loops come into play. Unlike other programming languages, Go has only single construct for looping, **`for`**

### Traditional loop

We can write traditional for loop using loop variable similar to most other programming languages.

`for initialization; condition; post statement {`&#x20;

`code to execute`&#x20;

`}`

{% code title="main.go" %}

```go
for i := 1; i < 10; i++ {
    fmt.Printf("Hello %d \n", i)
}
```

{% endcode %}

### For loop as while loop

We can only define the condition part in for loop and it will act like a while loop. We need to make sure initialization if any required as well as post conditioned are handled.

`for condition { code to execute }`

{% code title="main.go" %}

```go
j := 1
for j < 10 {
	fmt.Printf("Hello %d\n ", j)
	j = j + 1
}
```

{% endcode %}

If we skip the line 4 above, we end up creating infinite loop.

### Continue and Break

We can use continue and break statement inside of for loop to control flow.  `continue` is used to run next iteration of loop and abandon remaining code in current loop iteration. `break` is used to break out of the loop.

{% code title="main.go" %}

```go
for k := 1; k < 20; k++ {
	if k%2 == 0 {
		continue
	}
	fmt.Printf("Hello  %d\n", k)
}
for k := 1; k < 20; k++ {
	if k == 13 {
		break
	}
	fmt.Printf("Hello  %d\n", k)
}
```

{% endcode %}

The first for loop above will not print if value is even and continue to next iteration. Second for loop will break the loop when k reaches 13.

### Infinite Loop

We can also skip condition part of for loop which will create infinite loop. Make sure there is way to break out of for loop when no condition is provided.

{% code title="main.go" %}

```go
for {
    fmt.Println("Hello!")
    // break based on some condition to exit infinite loop
}
```

{% endcode %}

### Iterating over range

Go can easily iterate over arrays,maps and slices using `range` keyword.

When iterating over slice, range returns index and value from slice.

{% code title="main.go" %}

```go
data := []string{"a", "b", "c"}
for index, value := range data {
	fmt.Println(index, value)
}
```

{% endcode %}

When iterating over maps, range returns key and value.

{% code title="main.go" %}

```go
capitals := map[string]string{
	"India":   "Pune",
	"England": "London",
	"U.S.":    "Washington",
}
for key, value := range capitals {
	fmt.Println(key, value)
}
```

{% endcode %}

range is also useful for getting each rune from string.

{% code title="main.go" %}

```go
greetings := "नमस्कार"
for _, char := range greetings {
	fmt.Printf("%c\n", char)
}
```

{% endcode %}


# 19. User Defined Types

### User Defined Type

We can defined our own type based on existing Go in-build types. We have declared `person` as user defined type based on struct. We are not limited to struct. We can define our type based on any other type as base type.

### Declaring our own type

We can declare our type using `type` keyword. It generally takes form of

`type type_name base_type`

{% code title="main.go" %}

```go
type marks int
type liters float64

var m1 marks
m1 = 20

var l1 liters
l1 = 3.4
```

{% endcode %}

`marks` and `liters` are types based on `int` and `float64` respectively.

> **Go defined types most often use structs as their underlying types, but they can also be based on ints, strings, booleans, or any other type. - Head First Go**


# 20. Arrays

collecting similar data

### Array Type

Arrays are one of the fundamental type in any programming languages. Arrays are generally used to store *list of things* of similar type.

In Go, an array is a fixed-length sequence of zero or more elements of a particular type. That means, at run-time array can not grow or shrink. Due to this limitation, arrays are rarely used directly in Go

### Declaring array&#x20;

While declaring array, we need to specify size and type of array.

Below are some of array declarations:

{% code title="main.go" %}

```go
var numbers [8]float64
var days [5]string
var marks [10]int
```

{% endcode %}

1st line declares array named `numbers` which can hold up-to 8 `float64` values.

2nd declares array named `songs` which can hold up-to 5 `string` values&#x20;

### Accessing array elements

Since an array is collection of item, individual items of an array can be accessed by using square brackets `[]` with an index that begins at `0`

{% hint style="danger" %}
Remember array index starts at `0` and not `1`
{% endhint %}

{% code title="main.go" %}

```go
var days [7]string
// days[0] is the first element
days[0] = "Sunday"
// days[6] is the last element
days[6] = "Saturday"
```

{% endcode %}

If we try to access an element out or array index, Go compiler will give us error

{% code title="main.go" %}

```go
days[7] = "Funday"

```

{% endcode %}

`output: invalid array index 7 (out of bounds for 7-element array)`

### Zero Values

When a new array is created, all the values are initialized to the zero value for the type. Zero Values ensures that array is not uninitialized.

{% code title="main.go" %}

```go
var numbers [8]float64
var marks [10]int
fmt.Println(numbers, marks) 
// both numbers and marks elements get their zero values
//output : [0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0]
```

{% endcode %}

### Array Literals

We can assign values to an array while declaring using Array Literals.

{% code title="main.go" %}

```go
var data [2]string = [2]string{
		"Hello",
		"World!",
	}
```

{% endcode %}

Short variable declaration can also be used for array declaration

{% code title="main.go" %}

```go
newData := [2]string{"Hello", "World"}
fmt.Println(newData)
// output [Hello World!]
```

{% endcode %}

### Ellipsis

&#x20;if an ellipsis “`...`” appears in place of the length, the array length is determined by the number of elements

{% code title="main.go" %}

```go
arr := [...]string{"Hello", "World", "From Go"}
fmt.Println(arr)
	
```

{% endcode %}

### Iterating over Array

We can use traditional index to iterate over an array.When accessing array elements using a index variable, we need to be careful. Trying to access an index that is outside the array will cause a run-time panic!

{% code title="main.go" %}

```go
days = [7]string{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}

for index := 0; index < 7; index++ {
    fmt.Println(days[index])
}
```

{% endcode %}

A safer way is to use `len()` function to calculate length of array being iterated.

{% code title="main.go" %}

```go
for index := 0; index < len(days); index++ {
    fmt.Println(days[index])
}
```

{% endcode %}

A more idiomatic way is to use `for...range` to loop over an array. `range` returns each array index and item.&#x20;

{% code title="main.go" %}

```go
for i, day := range days {
		fmt.Println(i, day)
	}
```

{% endcode %}

If index is not required, it can be ignored using blank identifier

{% code title="main.go" %}

```go
for _, day := range days {
		fmt.Println(day)
	}
```

{% endcode %}

### Type Of Array

Type of array is determined by what type of data array stores as well as length of array. If two array's store same type of data but have different lengths, Go will treat those arrays as of two different types.

{% code title="main.go" %}

```go
greetings := [...]string{"Hello", "World"}
greetings = [...]string{"Hello", "World", "From Go"}
//output : cannot use [3]string literal (type [3]string) as type [2]string in assignment
```

{% endcode %}

### Comparing Arrays

Arrays of similar types can be compared using `==` and `!=` . Remember, for arrays to be to of similar types, they need to store same type of data as well as their length must be same.&#x20;

{% code title="main.go" %}

```go
a := [2]string{"Hello", "World"}
b := [...]string{"Hello", "World"}
fmt.Println(a == b)
```

{% endcode %}

### GitHub Code

{% embed url="<https://github.com/gophersumit/codewithgo-samples/blob/master/array/main.go>" %}

### Blog Posts

{% embed url="<https://blog.golang.org/slices>" %}


# 21. Slices

A window into an array!

### Slice Type

Array size is fixed in Go. We can not add more elements to an existing array. This is limiting from a programmer's point of view. Go provides slices to address this concern.

Slices in Go can grow. Arrays are fixed length sequence where as slices are variable length sequence in Go. Slices are very lightweight data structures.A slice has three components: a pointer, a length, and a capacity.&#x20;

### Declaring slice

While declaring slice, we need to specify type of element slice will hold with empty pair of `[]`.

&#x20;`[]T` defines a slice of type T.

{% code title="main.go" %}

```go
func printSlice(s []string) {
	fmt.Printf("size: %v, capacity:%v,value:%v\n",
		len(s), cap(s), s)
}
func main() {
	// declaring slice
	var names []string
	printSlice(names)
	//output size: 0, capacity:0,value:[]
}
```

{% endcode %}

While declaring an array, we need to specify size while slice declaration has empty size. `a` is an array below while `s` is a slice.

{% code title="main.go" %}

```go
var a [5]int
var s []int
```

{% endcode %}

### Creating slice

Declaring slice using var does not allocate backing array for slice. Instead, we have to create slice using `make` function. Make function accepts 3 parameters, first is type of slice, second is length of slice to create and optionally third parameter as capacity of slice.

`s := make([]T,length,capacity)`&#x20;

{% code title="main.go" %}

```go
names = make([]string, 5)
printSlice(names)
// output : size: 5, capacity:5, value:[    ]
```

{% endcode %}

If we know in advance, what capacity we need for slice, we can make slice with that capacity.

{% code title="main.go" %}

```go
names = make([]string, 5, 20)
printSlice(names)
// output : size: 5, capacity:20, value:[    ]
```

{% endcode %}

### Accessing slice elements

Since slice is window into an array, its elements can be accessed by using square brackets `[]` with an index that begins at `0` similar to array access.

{% code title="main.go" %}

```go
greetings := make([]string, 2)
greetings[0] = "Hello"
greetings[1] = "World"
printSlice(greetings)
// output: size: 2, capacity:2, value:[Hello World]
```

{% endcode %}

### Zero values

When new slice is created using `make` all its elements get initialized to its zero values.

{% code title="main.go" %}

```go
numbers := make([]float64, 8)
months := make([]string, 12)
fmt.Println(numbers)
fmt.Println(months)
// output : 
// numbers => [0 0 0 0 0 0 0 0]
// months => [           ]
```

{% endcode %}

### Slice literals

If  we know in advance what values a slice will start with, we can initialize the slice with those values using slice literal. We do not need to  `make` function call when using slice literals.

`[]T{values}`

{% code title="main.go" %}

```go
data := []string{
		"Hello",
		"World!",
	}
printSlice(data)
//out size: 2, capacity:2, value:[Hello World!]
```

{% endcode %}

### Slice from an existing array

We can create slice from an existing array. To create slice from existing array, we need to specify start index and end index using syntax `array[startIndex:endIndex]`

If starting index is zero, it can be skipped. If end index equals length of array, it can be skipped.

{% code title="main.go" %}

```go
days := [7]string{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}
	weekdays := days[0:5]
	// if first element of slice is same as first 
	//element of array, start index can be skipped
	weekdays = days[:5]
	printSlice(weekdays)

	weekend := days[5:7]
	// if last element of slice is same as last 
	// element of array, end index can be skipped
	weekend = days[5:]
	printSlice(weekend)

	alldays := days[0:7]
	// if slice has all array elements, both start 
	// index and end index can be skipped
	alldays = days[:]
	printSlice(alldays)
```

{% endcode %}

### Nil and empty slice

Go has both nil and empty slices. When we use var declaration, it initializes nil slice provided we do not use slice literal. If we use short variable declaration and create slice using make, it initializes empty slice. In case of nil slice, no backing array is created, while for empty slice backing array is present.

{% hint style="success" %}
use `len(s) == 0`, and not `s == nil`for checking for empty slice.
{% endhint %}

{% code title="main.go" %}

```go
// empty and nil slices
s := make([]string, 3)[3:]
var e []string
printSlice(s)
printSlice(e)

fmt.Println("Is s nil => ", s == nil)
fmt.Println("Is e nil => ", e == nil)
```

{% endcode %}

### Iterating over slice

Iteration over slice is similar to array iteration. Preferred way is to `for...range`

{% code title="main.go" %}

```go
// iterating over slices
for _, day := range alldays {
	fmt.Println(day)
}
```

{% endcode %}

### Type of slice and comparison

Unlike array, slice types are defined what type of data slice store. Comparison is not possible using `==` unlike arrays. For most use cases where comparison needs to be done, we need to write our own comparison code

{% code title="main.go" %}

```go
func testEquality(a, b []string) bool {
	if len(a) != len(b) {
		return false
	}
	for i := range a {
		if a[i] != b[i] {
			return false
		}
	}
	return true
}
```

{% endcode %}

### Append

The advantage slices have over arrays is the fact that slices can increase capacity and hold more elements at run-time. To add elements to slice, we use built in `append` function.

`append` can be used to add one or more elements to slice. Append operation may create new slice if new elements to add do not fit in existing capacity of slice.&#x20;

{% hint style="success" %}
Whenever we do append operation, we reassigned the returned slice to original slice. Returned slice may or may not be new slice.
{% endhint %}

`s := append(s, e)`

{% code title="main.go" %}

```go
s := make([]string, 0)
// appending elements
s = append(s, "a")
printSlice(s)
s = append(s, "e")
printSlice(s)
s = append(s, "i")
printSlice(s)
s = append(s, "o")
s = append(s, "u")
printSlice(s)
// output
// size: 1, capacity:1, value:[a]
// size: 2, capacity:2, value:[a e]
// size: 3, capacity:4, value:[a e i]
// size: 5, capacity:8, value:[a e i o u]
```

{% endcode %}

### GitHub Code

{% embed url="<https://github.com/gophersumit/codewithgo-samples/blob/master/slices/main.go>" %}

{% embed url="<https://github.com/quii/learn-go-with-tests/blob/master/arrays-and-slices.md>" %}

### Blog Posts

{% embed url="<https://blog.golang.org/go-slices-usage-and-internals>" %}

{% embed url="<https://www.ardanlabs.com/blog/2013/08/understanding-slices-in-go-programming.html>" %}

{% embed url="<https://www.ardanlabs.com/blog/2013/09/slices-of-slices-of-slices-in-go.html>" %}

{% embed url="<https://www.ardanlabs.com/blog/2013/09/iterating-over-slices-in-go.html>" %}

{% embed url="<https://github.com/golang/go/wiki/SliceTricks>" %}

### Videos

{% embed url="<https://www.youtube.com/watch?v=fhdA-6LcOxk>" %}


# 22. Structs

Working with different types together

### Struct Type

Slice and array are good for storing collection of data which is of same type. What if our data is made up of smaller types which are different? This is where struct comes in handy.A struct is a type that contains named fields. Struct is a value that is constructed out of other values of many different types.&#x20;

Slices and maps are used to store collection of similar data where as struct is used to groups together zero or more named values of arbitrary types as a single entity. Grouping together data of different types, that's where struct is useful.

### Declaring Struct

A simple struct can be constructed using `struct` keyword as

`struct {field type}`

{% code title="main.go" %}

```go
var person struct {
	name string
	age int
}
```

{% endcode %}

`name` and `age` are called fields of struct.

Generally, we will use multiple instance of struct in code. It is very common define struct as user defined type using `type` keyword for reuse.

{% code title="main.go" %}

```go
type person struct {
    name string
    age int
}
var p1 person
var p2 person
```

{% endcode %}

now `person` is a user defined `struct` type. `p1` and `p2` variables are both of type `person`.

### Creating struct

Declaring a variable of a particular struct type creates a struct. There is no explicit call required to any other function.

{% code title="main.go" %}

```go
var p1 person
var p2 person
fmt.Println(p1)
fmt.Println(p2)
```

{% endcode %}

### Accessing Struct Fields

Struct fields are accessed using dot operator `.` This can be used to read as well as write to struct fields.

{% code title="main.go" %}

```go
p1.name = "Joey"
p1.age = 30
fmt.Println(p1)
```

{% endcode %}

### Zero Values

When a struct is declared, it gets initialized to zero values for its all the fields.

{% code title="main.go" %}

```go
type show struct {
name        string
price       float64
isAvailable bool
rating      int
}
var s show
fmt.Printf("%#v\n", s)
// output
// main.show{name:"", price:0, isAvailable:false, rating:0}
```

{% endcode %}

### Struct literals

We can use struct literals to declare and initialize struct with initial value instead of zero value. We can define person struct type using struct literal as&#x20;

{% code title="main.go" %}

```go
var p3 person = person{
		name: "Chandler",
		age:  32,
}
fmt.Printf("%#v\n", p3)
```

{% endcode %}

### Comparing structs

Two structs of same type are comparable if and only if all the fields of the struct are comparable using `==.`

{% code title="main.go" %}

```go
var p4 person = person{
	name: "Chandler",
	age:  32,
}
var p5 person = person{
	name: "Joey",
	age:  30,
}
fmt.Println("are p4 and p5 equal? ==>", p4 == p5)
```

{% endcode %}

### Struct as another struct field

Like we can use data types like integers ,floats and strings as fields for a struct, we can also user another struct as field for building new structs. This is useful for reusing already created user defined types.

{% code title="main.go" %}

```go
type human struct {
	name string
	age  int
}

type superHuman struct {
	human human
	power string
}

superman := superHuman{
	human: human{
		name: "Clark Kent",
		age:  30,
	},
	power: "Flying",
}

fmt.Printf("%#v\n", superman)
// output
// main.superHuman{human:main.human{name:"Clark Kent", age:30}, power:"Flying"}
```

{% endcode %}

Note that if we need to access name of superman we need to use `superman.human.name`

{% code title="main.go" %}

```go
fmt.Println(superman.human.name)
```

{% endcode %}

### Anonymous fields for struct

What if we wish to use `superman.name` instead of `superman.human.name` in above code? Go supports this by providing type embedding.  An inner struct that is stored within an outer struct using an anonymous field is said to be **embedded** within the outer struct.

We are embedding `human` type inside `superHero` type. There is no named field inside `superHero` to which we are assigning `human` type. Outside struct literal, we can access fields of `human` type directly as if these fields exists on `superHero`. This is called type promotion.

{% code title="main.go" %}

```go
type superHero struct {
	livesSaved int
	human // embedding type
}
batman := superHero{}
ironman := superHero{
	livesSaved: 100000,
	human: human{
		name: "Tony",
		age:  40,
	},
}

batman.name = "Bruce" // accessing embedded type's field
batman.age = 50 // accessing embedded type's field
batman.livesSaved = 100

fmt.Printf("%#v\n", batman)
fmt.Printf("%#v\n", ironman)
```

{% endcode %}

### Embedding Types

### Blog Post

{% embed url="<https://www.ardanlabs.com/blog/2014/05/methods-interfaces-and-embedded-types.html>" %}


# 23. Maps

Let's navigate!

### Map Type

Map is collection of key value pairs. It goes by various names in other programming languages like dictionaries in Python, objects in JavaScript etc.

Maps are represented as  `map[K]V`, where `K` and `V` are the types of its keys and values.

### Declaring Maps

We can declare `map` using var declaration. We are defining `string` to be keys for the map and `string` to be values. Since map is declared but not initialized with any value, it will be a `nil` map.&#x20;

{% code title="main.go" %}

```go
var capitals map[string]string
fmt.Println(capitals)
fmt.Println("is map nil ==>", capitals == nil)
```

{% endcode %}

### Creating map

Maps are created using `make` function call. `make` will perform the required memory allocation required to use map. We can add elements to map using `map[key] = value` semantics.&#x20;

{% code title="main.go" %}

```go
caps := make(map[string]string)
// we can also use var keyword as below
// var caps map[string]string = make(map[string]string)
fmt.Println(caps)
fmt.Println("is map nil ==>", caps == nil) 
// returns false
caps["India"] = "Delhi"
caps["England"] = "London"
caps["U.S."] = "Washington"
fmt.Println(caps)
```

{% endcode %}

### Map Literals

We can also use map literal to declare and initialize maps. `make` function call is not required when using map literal.

{% code title="main.go" %}

```go
capitalsOfCountries := map[string]string{
    "India":   "Delhi",
    "England": "London",
    "U.S.":    "Washington",
}
fmt.Println(capitalsOfCountries)
```

{% endcode %}

### Accessing map elements

map elements can be accessed using subscript notion similar to array and slices. In array and slices, index can only be integers. For maps, however, key can be anything which can be compared using `==` comparison.

{% code title="main.go" %}

```go
//accessing map elements
fmt.Println(capitalsOfCountries["India"])
fmt.Println(capitalsOfCountries["England"])
```

{% endcode %}

If we try to access map key which does not exists, it will not cause an error, but will return zero value.

{% code title="main.go" %}

```go
fmt.Println(capitalsOfCountries["XYZ"]) 
// prints empty string
```

{% endcode %}

### Zero values for map

Zero value for map is nil. Zero value for map element is zero value for type being stored as value.

{% code title="main.go" %}

```go
var s map[string]string
var i map[string]int
fmt.Println("is s nil =>", s == nil)
fmt.Println("is i nil =>", i == nil)
```

{% endcode %}

If map is not nil, but empty, accessing its elements will returns its zero value.

{% code title="main.go" %}

```go
// zero value for map elements
j := map[string]int{}
fmt.Println(j["India"]) // output : 0

```

{% endcode %}

Notice that, event if key does to exist in empty map, it did return zero value.

### Nil and empty map

Similar to slices, maps can be empty or nil. When we use make function call or use map literal for declaring map, it initializes empty map

{% code title="main.go" %}

```go
var t = make(map[string]string)
k := map[string]int{}
fmt.Println("is t nil =>", t== nil)
fmt.Println("is k nil =>", k== nil)
```

{% endcode %}

Both `nil` and empty maps have `len()` as zero.

{% code title="main.go" %}

```go
var s map[string]string
var t = make(map[string]string)
fmt.Println(len(s))
fmt.Println(len(t))
```

{% endcode %}

### Iterating over map

Iterating over maps is similar to array and slices, we can use `for...range` loop for iteration. `range` works as follows for a map

`for key,value :=range map { // }`

{% code title="main.go" %}

```go
for key, value := range caps {
	fmt.Printf("key =>%v, value => %v\n", key, value)
}
```

{% endcode %}

{% hint style="danger" %}
Unlike arrays and slices, maps do not guarantee same order. Map is unordered collection of key-value pairs.
{% endhint %}

If either key or value is not required, we can omit it by using blank identifier.

{% code title="main.go" %}

```go
for _, value := range caps {
	fmt.Printf("value => %v\n", value)
}
for key, _ := range caps {
	fmt.Printf("key =>%v\n", key)
}
```

{% endcode %}

### Finding element in map

To find element in map, we provide key to the map to get element/value returned from map. A map does not panic if we try to access key which is not present, instead it returns zero value. To identify if value is returned is actual value present on map or zero value returned due to absence of key, map returns a second value, `ok` which tells if key was found or not. &#x20;

If we see output for below code snippet, when we check for `XYZ` and `ABC`, both returns empty string. For `XYZ`, value is empty string, while for `ABC`, it is missing from map.

{% code title="main.go" %}

```go
cocs := map[string]string{
		"India":   "Delhi",
		"England": "London",
		"U.S.":    "Washington",
		"XYZ":     "",
	}

fmt.Printf("Checking captial for India-> %v\n",
	cocs["India"])
fmt.Printf("Checking captial for XYZ-> %v\n",
	cocs["XYZ"])
fmt.Printf("Checking captial for ABC-> %v\n",
	cocs["ABC"])
```

{% endcode %}

To distinguish between empty/zero value and missing value, we can use `value,ok` semantics.

{% code title="main.go" %}

```go
value, ok := cocs["XYZ"]
if ok {
	fmt.Printf("Value is %v \n", value)
} else {
	fmt.Println("Key not found")
}
value, ok = cocs["ABC"]
if ok {
	fmt.Printf("Value is %v \n", value)
} else {
	fmt.Println("Key not found")
}
```

{% endcode %}

### Updating element in map

Updating value is similar to creating a value. We can use&#x20;

`map[key]= value` semantic to update value for given key.

{% code title="main.go" %}

```go
capitals = map[string]string{
		"India":   "",
		"England": "London",
		"U.S.":    "Washington",
}
capitals["India"] = "Delhi"
fmt.Println(capitals)
```

{% endcode %}

### Deleting element from map

Deleting value from map is straightforward. Go provides inbuilt delete function to delete a value from map. Semantics for delete is&#x20;

`delete(mapName,key)`

{% code title="main.go" %}

```go
capitals = map[string]string{
		"India":   "Pune",
		"England": "London",
		"U.S.":    "Washington",
}

delete(capitals, "England")
fmt.Println(capitals)
```

{% endcode %}

### Comparing maps

Similar to slices, maps can not be compared directly. We can only check if a map is nil or not directly. For other comparisons, we need to write our own for loop for comparison.

### GitHub Code

{% embed url="<https://github.com/gophersumit/codewithgo-samples/tree/master/maps>" %}

### Blog Posts

{% embed url="<https://blog.golang.org/go-maps-in-action>" %}

{% embed url="<https://www.ardanlabs.com/blog/2013/12/macro-view-of-map-internals-in-go.html>" %}

### Videos

{% embed url="<https://www.youtube.com/watch?v=Tl7mi9QmLns>" %}
GopherCon 2016: Keith Randall - Inside the Map Implementation
{% endembed %}


# 24. Functions

### Functions&#x20;

Functions are basic construct in most of the programming language. It a way of organizing code for reuse. Simple put, function is a named code block which can be called. We have seen in-build functions like `fmt.Println()` We can also define our own functions.

### Main Function

We use `func` keyword. We have seen `func` keyword before in our code with `main`. `main()` is a special function which is required for every executable Go code.

{% code title="main.go" %}

```go
package main

import "fmt"

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

{% endcode %}

### Declaring Functions

Functions are declared using `func` keyword followed by name of function. A function need to have a body, which defines code statements to execute when called.

{% code title="main.go" %}

```go
func sayHello(){
    fmt.Println("Hello")
}
```

{% endcode %}

`sayHello` is a function which will print `Hello` when called.

### Calling Function

Calling function is a way to execute our function. A function can be called multiple times if required. To call a function, we simply use name of function followed by pair of round brackets `()`

{% code title="main.go" %}

```go
package main

import "fmt"

func sayHello() {
	fmt.Println("Hello")
}
func main() {
	sayHello()
}
```

{% endcode %}

On line 9, we have called `sayHello.`

### Passing Data

A function can accept input to work upon. We can pass data to a function in the form of what are called function parameters. It follows syntax

`func func_name(parameter_list) { func_body }`

Parameter list is comma separated list of parameter. Each parameter need to define name of parameter and type of parameter.

`(paramter_name_1 paramter_type, parameter_name_2 parameter_type)`

{% code title="main.go" %}

```go
package main

import "fmt"

func sayHello(message string) {
	fmt.Println(message)
}
func main() {
	sayHello("Hello, World!")
}
```

{% endcode %}

`message` is the name of parameter and it will store `string` values passed to it.

while calling function, we need to pass string as

`sayHello("Hello, World!")`

### Returning Data

Function can accept data using function parameters. Similarly, function can also return data using return value.&#x20;

`func func_name(parameter_list) (return_list) { func_body }`

In Go, a function can return multiple values. Similar to parameter list, we can also define return list. It can be defined as comma separated list of types that function will return.

`(return_type1, return_type2, return_type3)`

Once data is returned, we will also need to store this data from where we are calling this function.

{% code title="main.go" %}

```go
package main

import "fmt"

func sayHello(message string) string {
	fmt.Println(message)
	return "I have printed!"
}
func main() {
	var result string
	result = sayHello("Hello, World!")

	fmt.Println(result)
}
```

{% endcode %}

function `sayHello` returns a `string.` We have defined `result` as type of `string` as local variable for our `main` function. When `sayHello` returns `string`, it is being stored in result variable.

### Returning Error

Since Go can return multiple values, an error is returned if function has encountered an error while executing. Errors may happen to various reasons. A common example is reading a file. Say if we try to read from a file and that file does not exist.

{% code title="main.go" %}

```go
package main

import (
	"fmt"
	"io/ioutil"
)

func readFile(fileName string) (string, error) {
	data, err := ioutil.ReadFile(fileName)
	return string(data), err
}
func main() {
	result, err := readFile("hello.txt")

	if err != nil {
		fmt.Println(result)
	}
}
```

{% endcode %}

`readFile` function return 2 values a `string` and an `error`. While calling this function, we need to provide 2 variables which will capture this return values. We have used `result` and `err` variable to store these values.

### Anonymous Functions

Go supports anonymous functions. These are functions without any names. They let us define a function at its point of use. Anonymous functions defined have access to the entire lexical environment also called as Closure.

{% code title="main.go" %}

```go
package main

import "fmt"

func main() {
	var hello string

	func() {
		fmt.Println("I am anonymous function!")
		hello = "Hello, World!"
	}()

	fmt.Println(hello)
}
```

{% endcode %}

We have anonymous function which is declared and called inside main function.

### Blog Posts

{% embed url="<https://blog.golang.org/first-class-functions-in-go-and-new-go>" %}

{% embed url="<https://blog.gophersumit.com/fun-with-go-functions-cjz1ogmcg0008mgs1yzm5h6l5>" %}

{% embed url="<https://www.ardanlabs.com/blog/2013/10/functions-and-naked-returns-in-go.html>" %}


# 25. Defer

Wait Until I am done!

### Defer Statement

`defer` is special keyword in Go to schedule some action until function returns. Defer is mostly used in cleanup task that should be done when returning from a function. Defer find its use similar to what finally does in some programming languages. Semantic for defer is&#x20;

`defer some_action`

{% code title="main.go" %}

```go
func sayHello() {

	defer fmt.Println("Performing cleanup")
	fmt.Println("Hello, There!")

}
func main() {
	sayHello()
}
```

{% endcode %}

Here, call to print cleanup is scheduled to be executed when function returns. Hello, There is printed first and then Performing cleanup.

### Panic scenarios

The benefit of using `defer` keyword is that Go guarantees it will be carried out even if there is panic.

{% code title="main.go" %}

```go
func doPanic() {
	defer fmt.Println("Performing cleanup")
	panic("Oops")
	fmt.Println("Hello, There")
}
func main() {
	doPanic()
}
```

{% endcode %}

In this case, defer will still print Performing cleanup.

### Blog Posts

{% embed url="<https://blog.learngoprogramming.com/gotchas-of-defer-in-go-1-8d070894cb01>" %}

{% embed url="<https://blog.learngoprogramming.com/5-gotchas-of-defer-in-go-golang-part-ii-cc550f6ad9aa>" %}

{% embed url="<https://blog.golang.org/defer-panic-and-recover>" %}


# 26. Pointers

Sharing!

### Pointers&#x20;

Pointers is is type of variable in Go. Instead of string a value type, pointer stores address of another variable. Pointer points to address of another variable in Go. To get address of variable, we use `&` operator. To get value that pointer points to, we use `*` operator.

{% code title="main.go" %}

```go
a := 10
b := &a
fmt.Printf("Value of a is %d \n", a)
fmt.Printf("Address of a is %v\n", &a)
fmt.Printf("Value at pointer location is %v\n", *b)
```

{% endcode %}

### Pointer Type

Like we can declare variables to hold different types of values in Go, we can also declare pointer that holds address of different Go types. Variable `intP` is pointer to `int` type while `floatP` is pointer to `float64` type. Similar to value types, we can not assign pointer of type X to pointer of type Y.

{% code title="main.go" %}

```go
var intP *int
var floatP *float64
fmt.Println(intP, floatP)
```

{% endcode %}

### Pointer to structure

It is common to use Pointers with struct in Go. Since it is common use case, for de-referencing (getting value out of pointer) Go does not require us to use asterisk `(*)` symbol. Instead of  `(*myLocation).street` we can use `myLocation.street`

{% code title="main.go" %}

```go
type location struct {
	street  string
	city    string
	pincode int
}

myLocation := &location{
	street:  "Xyz",
	city:    "Pune",
	pincode: 444101,
}

fmt.Printf("I live on %s street, %s city with %d code\n",
	myLocation.street, myLocation.city, myLocation.pincode)
```

{% endcode %}

### Sharing Data

Main use of pointers is to share data between function calls. Pointers when used efficiently help us increase system performance by sharing data instead of making a fresh copy every time between function calls. `updateLocation` function accepts pointer to `location` type and it can update `myLocation` variable value using pointer.

{% code title="main.go" %}

```go
type location struct {
	street  string
	city    string
	pincode int
}
func main() {
	myLocation := &location{
		street:  "Xyz",
		city:    "Pune",
		pincode: 444101,
	}

	fmt.Printf("I live on %s street, %s city with %d code\n",
		myLocation.street, myLocation.city, myLocation.pincode)

	// sharing data
	updateLocation(myLocation)

	fmt.Printf("I live on %s street, %s city with %d code\n",
		myLocation.street, myLocation.city, myLocation.pincode)
}

func updateLocation(loc *location) {
	loc.city = "Mumbai"
}
```

{% endcode %}

### Blog Resources

{% embed url="<https://www.ardanlabs.com/blog/2013/07/understanding-pointers-and-memory.html>" %}

{% embed url="<https://www.ardanlabs.com/blog/2014/12/using-pointers-in-go.html>" %}

{% embed url="<https://www.ardanlabs.com/blog/2017/05/language-mechanics-on-stacks-and-pointers.html>" %}


# 27. Methods

Functions on type

### Methods

In Go, methods are functions which are attached to a particular type. This gives functionality similar to Object Oriented Programming. Since methods are attached to particular type, we can reuse method name to attach them to different types.

### Declaring Methods

Method declaration is similar to function declaration, but in addition we need to provide the type to which this method is attached to. This type is called receiver.

`func (receiver type) name() { code to execute}`

First declaration below is a function `sayHello`, while second declaration is method `sayHello.`

{% code title="main.go" %}

```go
type user struct {
	name string
}

func sayHello(u user) {
	fmt.Printf("Hello, %s from function \n", u.name)
}

func (u user) sayHello() {
	fmt.Printf("Hello, %s from method\n", u.name)
}

func main() {
	u := user{
		name: "Gopher",
	}
	// function call
	sayHello(u)
	// method call
	u.sayHello()
}
```

{% endcode %}

### Pointer Receiver

We use pointer to share data to avoid unnecessary copy operation on data. Similarly, pointer receivers are used so that method can operate directly operate on data without making copy operation. We are passing pointer to user and `updateUser` method updates the same value. that we have created in `main` function.

{% code title="main.go" %}

```go
func (u *user) updateUser() {
	u.name = "Bob"
}

func main() {
	u := &user{
		name: "Gopher",
	}
	u.updateUser()
	fmt.Println(u.name)
}

```

{% endcode %}


# Resources - Paid

Awesome Go Resources

## Books

### Beginners Books

{% embed url="<http://shop.oreilly.com/product/0636920046516.do>" %}

{% embed url="<https://www.manning.com/books/get-programming-with-go>" %}

{% embed url="<http://shop.oreilly.com/product/0636920054931.do>" %}

### Intermediate Books

{% embed url="<https://www.manning.com/books/go-in-action>" %}

{% embed url="<https://learning.oreilly.com/library/view/the-go-programming/9780134190570/>" %}

{% embed url="<http://www.informit.com/store/go-programming-language-phrasebook-9780321817143>" %}

{% embed url="<https://www.packtpub.com/application-development/go-programming-blueprints>" %}

### Advanced Books

{% embed url="<https://www.manning.com/books/go-in-practice>" %}

{% embed url="<http://shop.oreilly.com/product/0636920046189.do>" %}

{% embed url="<https://www.manning.com/books/go-web-programming>" %}

## Video Course

### Introductory courses

{% embed url="<https://app.pluralsight.com/library/courses/go-big-picture/table-of-contents>" %}

{% embed url="<https://app.pluralsight.com/library/courses/getting-started-with-go/table-of-contents>" %}

{% embed url="<https://app.pluralsight.com/library/courses/go-fundamentals/table-of-contents>" %}

{% embed url="<https://learning.oreilly.com/videos/learning-path-go/9781491958100>" %}

### Intermediate Courses

{% embed url="<https://app.pluralsight.com/library/courses/go-cli-playbook/table-of-contents>" %}

{% embed url="<https://app.pluralsight.com/library/courses/go-delve-debugging-applications/table-of-contents>" %}

{% embed url="<https://app.pluralsight.com/library/courses/go-object-oriented-programming/table-of-contents>" %}

{% embed url="<https://learning.oreilly.com/videos/intermediate-go-programming/9781491944073>" %}

{% embed url="<https://app.pluralsight.com/library/courses/exploring-go-modules/table-of-contents>" %}

### Advanced Courses

{% embed url="<https://app.pluralsight.com/library/courses/go-concurrent-programming/table-of-contents>" %}

{% embed url="<https://app.pluralsight.com/library/courses/go-packages-deep-dive/table-of-contents>" %}

{% embed url="<https://app.pluralsight.com/library/courses/go-horizontal-scaling-apps/table-of-contents>" %}

{% embed url="<https://app.pluralsight.com/library/courses/go-testing-applications/table-of-contents>" %}

{% embed url="<https://app.pluralsight.com/library/courses/go-build-distributed-applications/table-of-contents>" %}

{% embed url="<https://learning.oreilly.com/videos/ultimate-go-programming/9780135261651>" %}

## Bundles

{% embed url="<https://www.usegolang.com/>" %}

{% embed url="<https://testwithgo.com/>" %}

{% embed url="<https://www.coursera.org/specializations/google-golang>" %}

{% embed url="<https://www.udemy.com/course/learn-how-to-code/>" %}


# Resources - Free

## Books

### Beginner Books

{% embed url="<http://www.golang-book.com/books/intro>" %}

{% embed url="<http://www.golangbootcamp.com/>" %}

{% embed url="<https://tour.golang.org>" %}

{% embed url="<https://gobyexample.com/>" %}

{% embed url="<https://www.miek.nl/go/>" %}

{% embed url="<https://www.openmymind.net/The-Little-Go-Book/>" %}

### Intermediate Books

{% embed url="<https://github.com/quii/learn-go-with-tests>" %}

{% embed url="<https://leanpub.com/antitextbookGo/>" %}

{% embed url="<http://www.pazams.com/Go-for-Javascript-Developers/>" %}

### Advanced Books

{% embed url="<https://checkmarx.gitbooks.io/go-scp/>" %}

{% embed url="<https://dave.cheney.net/high-performance-go-workshop/dotgo-paris.html>" %}


