Golang for Experienced Developers
Tags: go, tutorial, programming, beginners
Published: 2021-09-20 15:39:41

### Hello World,

Today I am going to start a Golang tutorial series. I am an experienced Java Developer however my job required me to learn Golang so I will be documenting my learning journey in a structured format. In this series, we'll go from absolute basics to somewhat intermediate in Golang. This is the first place you should start if you have just heard of the name "Golang" but never got a chance to learn it.

---
## Go: Pros & Cons
Suppose C++, Java & Python had a child, they named it Go and so it inherits features from each one of these languages. Here are some of them:

1. C-like Syntax, therefore Concise & Clean
2. Garbage Collection, therefore Memory Safety
3. Package Model, therefore Faster Builds  
4. Statically Typed, therefore Type Safety
5. Free & Open Source, therefore More Support

**Here is What Go Lacks?**
1. No overloading of functions & operators
2. No classes & inheritance
3. No exception handling 
4. No support for pointer arithmetic

After reading these counter statements you might be wondering why would someone go with Go(pun intended), check [this](https://blog.astradot.com/why-we-moved-from-kotlin-spring-boot-to-go/) & [this](https://faun.pub/building-enterprise-grade-microservice-using-go-golang-51a4e27ed199) out and you will know why.

---

## Let's "Go" to First Program
```
package main
import "fmt"

func main() {
    fmt.Println("Hello World!");
}
```
######Points to remember:
* `main` is the first function that gets executed, similar to any other programming language.
* `fmt` is a format library in-built in Go, it's used for formatted printing & more.
* `import` statement is used to import external libraries in Go, like Java.
* `package` is used for modularisation of Go programs, like Java.

### Go Run & Go Build
Now it's time to build & run the program we just wrote, for this purpose we need to make sure we have Go installed in our system, you can refer [this](https://golang.org/doc/install) to install Go in your system.

###### Building Go Programs
> $ go build main.go 

This command will build your Go program into system native executable named same as your program file name (main.go), you can run the executable directly by calling the executable (main).

> $ go build -ldflags "-s -w" main.go

The ldflags stand for linker flags, it passes flags to underlying Go toolchain linker. The flags `-s` & `-w` will disable creation of symbol tables for the compiler and hence reduce down the size of the executable. 

###### Running Go Programs
> $ go run main.go   

This command will first build your Go program in system temp location & run it to show the output, once the run is completed, the build is discarded. In other words, this will simply run your Go program.

---

## How Does Go Work?
Go programs doesn't require a VM to run like how Java runs on JVM, Go compiles the program into native executables that are specific to the system therefore Go doesn't support platform independence. However the load falls on the developer to build executables for Windows, Linux & Darwin systems.

---

## Basics
Any Go program consists of:
* Keywords
* Identifiers
* Data Types
* Constants
* Variables
* Operators 
* Functions


### Keywords

The following keywords are reserved and may not be used as identifiers.

```
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
```

### Identifiers
Identifiers name program entities such as variables and types.

* An identifier is a sequence of one or more letters and digits.
* The first character in an identifier must be a letter.

Some identifiers are predeclared.

###### Predeclared Identifiers:

```
Types:
	   bool byte complex64 complex128 error float32 
       float64 int int8 int16 int32 int64 rune 
       string uint uint8 uint16 uint32 uint64 uintptr

Constants:
	   true false iota

Zero value:
	   nil _

Functions:
	   append cap close complex copy delete imag len
	   make new panic print println real recover
```

### Data Types
```
Primitives: 
           int, complex, float, bool, string
Structured:
           struct, array, slice, map, channel
```

> NOTE: We'll cover each data type in further tutorials.

### Constants

The syntax to define a constant in Go is as follows:

```
const identifier type = value
```
###### Points to remember:
* Constants must be evaluated at compile time.
* The `type` is optional as compiler will guess the type based on value at compile time.
* Applies only to primitive data types.
* Can be enumerated with `iota` identifier.

###### Examples:

```
const c1 = "this is a constant string." // type is optional

const c2 float32 = 5/6. // period(.) at the end tells compiler to do float arithmetic instead of integer arithmetic.

const billion = 1e9 // possible

const funcValue = funcThatReturnValue()   // compile time error, why? 

const(one, two = 1, 2) // can combine various constant initialisation into once

const (           // using iota for enumeration
    zero = iota   // 0
    one           // 1
    two           // 3
    three         // 4
)
```

### Variables

The syntax to define a variable in Go is as follows:

```
var identifier type = value
```
###### Points to remember:
* If `value` is not supplied, `type` is required.
* If `type` is not supplied, `value` is required.
* Variables are always initialised to default values (0 or nil).
* Variables declared inside functions have local scope.
* Variables declared outside functions have global scope(package scope).

###### Examples:
```
var variable1 int   // syntactically ok

var variable2       // missing value & type, compile time error

var value = 3.48    // ok, defaults to float64 type

var isSet bool = false  // ok

var (                  // can combine various variable declaration into once
    radius int
    isSet bool
    name string
)
```

### Operators:

Following is the list of operators & delimiters in Go:
```
-    |    +    &    *    ^    /    <<    /=    <<=    ++    =
%    >>    %=    >>=    --    !    &^    &^=    +=    &=    -= |=    *=    ^=    &&    ==    !=    (    )    ||    <    <-   
>    <=    [    ]    >=    {    }    :=    ,    ;  ...    .  :
```

###### Operator Precedence:
```
Precedence    Operator
    5             *  /  %  <<  >>  &  &^
    4             +  -  |  ^
    3             ==  !=  <  <=  >  >=
    2             &&
    1             ||
```

#### Local Assignment Operator( := ):
The syntax for local assignment operator is as follows:
```
identifier := value
```
###### Points to remember:
* The local assignment operator ( := ) creates new variables and assign value.
* It doesn't need `type` details as the compiler does guess it for you.
* Local assignment operator must be used inside functions.

###### Example:
```
func main() {
    value := 50.5
    isSet := false
    x, y, z := 3, 56.5, "hello"   // x = 3, y = 56.5, z = "hello"
}
```

This concludes the first part of this tutorial series. Check out the second part [here](https://dev.to/livesamarthgupta/golang-for-experienced-developers-part-ii-2lj1) where I talked about all primitive data types and string handling.